React
What is React?
- A JavaScript library for building user interfaces.
- Component-based, declarative, and handles stateful applications.
JSX (JavaScript XML):
- Syntax extension that looks like HTML and allows embedding JavaScript expressions.
jsxconst element = <h1>Hello, World!</h1>;
Components:
- Functional Components:
- Functions that return JSX.
jsxfunction MyComponent() { return <h1>Hello</h1>; }
- Class Components:
- ES6 classes that extend
React.Component
and require arender()
method.
jsxclass MyComponent extends React.Component { render() { return <h1>Hello</h1>; } }
- ES6 classes that extend
- Functional Components:
Props:
- Properties passed from parent to child components.
- Read-only, used for rendering dynamic data.
jsxfunction Welcome(props) { return <h1>Hello, {props.name}</h1>; }
jsx<Welcome name="John" />
State:
Holds data that can change over time and trigger UI updates.
For class components:
jsxclass MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return <h1>{this.state.count}</h1>; } }
For functional components using hooks:
jsxconst MyComponent = () => { const [count, setCount] = useState(0); return <h1>{count}</h1>; };
React Hooks (Functional Components):
useState
:- Manages state in functional components.
jsxconst [count, setCount] = useState(0);
useEffect
:- Side effects like data fetching, subscriptions, etc.
- Runs after rendering and can optionally clean up or run only on certain updates.
jsxuseEffect(() => { // Component did mount return () => { // Component will unmount (cleanup) }; }, [count]); // Optional dependency array
useContext
:- Used to consume values from a React
Context
without passing props manually.
jsxconst value = useContext(MyContext);
- Used to consume values from a React
useReducer
:- Alternative to
useState
for more complex state logic.
jsxconst [state, dispatch] = useReducer(reducer, initialState);
- Alternative to
useRef
:- Holds a reference to a DOM element or value between renders.
jsxconst inputRef = useRef();
useMemo
anduseCallback
:- Optimize performance by memoizing expensive computations or functions.
jsxconst memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); const memoizedCallback = useCallback(() => doSomething(), [dependency]);
Component Lifecycle Methods (Class Components):
- Mounting (component creation):
constructor()
componentDidMount()
: Called after the component is rendered.
- Updating (re-rendering):
componentDidUpdate()
: Invoked after updating state or props.
- Unmounting (component removal):
componentWillUnmount()
: Cleanup before the component is removed from the DOM.
Forms & Events:
Handling Events:
- Similar to DOM events but in camelCase.
jsxfunction handleClick() { console.log("Button clicked"); } <button onClick={handleClick}>Click Me</button>;
Controlled Components:
- Form inputs whose value is controlled by React state.
jsxconst [value, setValue] = useState(""); return <input value={value} onChange={(e) => setValue(e.target.value)} />;
Uncontrolled Components:
- Form inputs where React does not control the value. Uses
ref
to access DOM elements directly.
jsxconst inputRef = useRef(); const handleSubmit = () => { console.log(inputRef.current.value); }; return <input ref={inputRef} />;
- Form inputs where React does not control the value. Uses
Conditional Rendering:
if/else
Rendering:jsxif (isLoggedIn) { return <Dashboard />; } else { return <Login />; }
Ternary Operator:
jsxreturn isLoggedIn ? <Dashboard /> : <Login />;
Short-circuit (
&&
) Rendering:jsxreturn isLoggedIn && <Dashboard />;
Lists and Keys:
Rendering Lists:
jsxconst list = [1, 2, 3]; return ( <ul> {list.map((item) => ( <li key={item}>{item}</li> ))} </ul> );
Keys:
- Unique identifiers to help React track and optimize list re-rendering.
- Always use a unique key for each list item.
React Router:
Routing in React:
- Enables navigation between different views.
bashnpm install react-router-dom
Basic Example:
jsximport { BrowserRouter as Router, Route, Switch } from "react-router-dom"; function App() { return ( <Router> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); }
React Context API:
Context Setup:
- Provides a way to pass data through the component tree without prop drilling.
jsxconst MyContext = React.createContext();
Providing Context:
jsx<MyContext.Provider value={value}> <MyComponent /> </MyContext.Provider>
Consuming Context:
- Using
useContext
in functional components.
jsxconst value = useContext(MyContext);
- Using
Styling in React:
Inline Styles:
jsx<div style={{ color: "red", fontSize: "20px" }}>Hello</div>
CSS Modules:
- Scoped CSS with unique class names.
css/* styles.module.css */ .myClass { color: red; }
jsximport styles from "./styles.module.css"; <div className={styles.myClass}>Hello</div>;
Styled Components:
- CSS-in-JS library for dynamic styling.
bashnpm install styled-components
jsximport styled from "styled-components"; const Button = styled.button` background-color: blue; color: white; `; <Button>Click Me</Button>;
Performance Optimization:
React.memo()
:- Memoizes functional components to prevent unnecessary re-renders.
jsxconst MyComponent = React.memo(function (props) { return <div>{props.name}</div>; });
shouldComponentUpdate()
:- Used in class components to prevent re-rendering when unnecessary.
jsxshouldComponentUpdate(nextProps, nextState) { return nextProps.value !== this.props.value; }
Code Splitting (Dynamic Imports):
- Load components dynamically to reduce the initial load.
jsxconst OtherComponent = React.lazy(() => import("./OtherComponent")); <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense>;
React Fragments:
- Avoids unnecessary div wrappers around components.jsx
return ( <React.Fragment> <h1>Title</h1> <p>Content</p> </React.Fragment> );
Media Queries (with CSS-in-JS):
Use media queries in JS with styled components or inline styles.
jsxconst Container = styled.div` width: 100%; @media (max-width: 768px) { width: 50%; } `;
Component-Based Architecture: Reusable components for building UI.
Hooks: Enable state and side effects in functional components.
React Router: For handling client-side routing.
Context API: Share data across components without passing props.
Performance Optimization:
React.memo()
, dynamic imports, anduseCallback()
.JSX: Combines HTML-like syntax with JavaScript expressions.