Components & Hooks
What is React?
React is a JavaScript library used to build user interfaces (UI).
Key Features
Component-based architecture
Reusable code
Fast rendering using Virtual DOM
Easy to manage large applications
Components in React
A component is a small, reusable piece of UI in React. Every React application is built by combining multiple components.
function Welcome() {
return <h1>Hello User</h1>;
}
Components are reusable
Each component manages its own logic
UI is divided into small independent parts
Functional vs Class Components
Class Component
Uses
this.statefor stateUses lifecycle methods (
componentDidMount, etc.)Requires
thiskeywordMore boilerplate code
import React, { Component } from "react";
class Counter extends Component {
state = { count: 0 }; // similar to useStae
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Count: {this.state.count}
</button>
);
}
}
Functional Component
Plain JavaScript function
Uses Hooks for state and lifecycle
No
thiskeywordSimple and clean code
Preferred in modern React
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
What are React Hooks?
Hooks are special functions that allow functional components to use state, lifecycle, and advanced features.
Why Hooks?
Remove need for class components
Make code cleaner
Reuse logic easily
Improve readability
Rules of Hooks
Only call hooks at the top level
Only call inside React functions
useState — Managing State
Important Terms
State — data that a component stores and manages
Re-render — React updates the UI when state changes
Initial value — the starting value given to useState
Setter function — the function used to update state (e.g.
setCount)
jsx
const [state, setState] = useState(initialValue);
jsx
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Key Points
count— stores the current state valuesetCount— updates the stateUpdating state triggers a re-render
State is preserved between renders
Can store: number, string, array, object
Use for: counter, form inputs, toggles
useEffect — Side Effects & Lifecycle
Important Terms
Side effect — any operation outside of rendering (API call, timer, DOM update)
Dependency array — controls when useEffect runs
jsx
// Run once on mount
useEffect(() => {
console.log("Mounted");
}, []);
// Run every render
useEffect(() => {});
// Run when value changes
useEffect(() => {}, [count]);
Key Points
Runs after the component renders
Used for side effects — not UI rendering
Controlled by the dependency array
Cleanup function prevents memory leaks
Replaces class lifecycle methods
| Dependency | When it runs |
|---|---|
| No array | Every render |
[] |
Once (on mount) |
[value] |
When value changes |
Use for: API calls, timers, event listeners, DOM updates
useRef — DOM Access
Important Terms
ref — a reference object created by useRef
.current — the property that holds the actual value or DOM element
Mutable value — a value that can be changed without causing re-render
jsx
function InputFocus() {
const ref = useRef(null);
return (
<>
<input ref={ref} />
<button onClick={() => ref.current.focus()}>Focus</button>
</>
);
}
Key Points
Value stored in
.currentDoes NOT trigger re-render
Directly accesses DOM elements
Value persists across renders
Use for: focus input, store previous values, access DOM
useReducer — Complex State
Important Terms
Reducer — a pure function that takes current state and an action, returns new state
Action — an object describing what change to make (e.g.
{ type: "inc" })dispatch — a function that sends an action to the reducer
Initial state — the starting value of the state object
jsx
function reducer(state, action) {
switch (action.type) {
case "inc": return { count: state.count + 1 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: "inc" })}>
{state.count}
</button>
);
}
Key Points
state— current statedispatch— sends an actionreducer— decides how state changesKeeps logic centralized and structured
Flow: dispatch → reducer → new state → UI update
Use for: complex logic, multiple state updates
useContext — Global Data
Important Terms
Context — a way to share data across components without passing props
Provider — wraps components and supplies the shared data
Consumer — any component that reads the context value
createContext — function used to create a new context
jsx
import { createContext, useContext } from "react";
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="user">
<Child />
</UserContext.Provider>
);
}
function Child() {
const name = useContext(UserContext);
return <h1>{name}</h1>;
}
Key Points
Shares data across components
Avoids prop drilling
Works with Provider and Consumer pattern
Any component can access data directly
Use for: user authentication, theme, global settings
useMemo — Performance Optimization
Important Terms
Memoization — caching the result of a function so it is not recalculated every time
Expensive calculation — a computation that takes noticeable time or resources
Dependency array — useMemo re-runs only when these values change
Cache — stored result that is reused instead of recalculated
import { useState, useMemo } from "react";
function App() {
const [num, setNum] = useState(2);
const square = useMemo(() => num * num, [num]);
return (
<>
<h1>Number: {num}</h1>
<h2>Square: {square}</h2>
<button onClick={() => setNum(num + 1)}>
Change Number
</button>
</>
);
}
export default App;
Key Points
Caches the result of a function
Prevents unnecessary recalculation
Runs only when dependencies change
Use for: expensive calculations, large data processing
useCallback — Function Optimization
Important Terms
Function recreation — React creates a new function on every render by default
Memoized function — a cached version of a function that is reused across renders
Child re-render — when a parent re-renders, child components may also re-render unnecessarily
Reference equality — React checks if a function is the same reference before re-rendering
jsx
import { useState, useCallback } from "react";
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
alert("Button clicked");
}, []);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={handleClick}>
Click Me
</button>
</>
);
}
Key Points
Caches the function definition
Prevents function recreation on every render
Avoids unnecessary child re-renders
Use for: passing functions to child components
