We are going to explain what React Hooks are and then focus on two of the most commonly used ones: useState and useEffect.
React Hooks: An Overview
React Hooks are functions that let you use state and other React features in functional components without writing a class. Introduced in React 16.8, they enable:
- State management in function components
- Side-effect handling (data fetching, subscriptions, DOM manipulation)
- Code reuse through custom hooks
- Cleaner, more readable code vs. class components
useState Hook
Purpose
Manages local component state in functional components.
Syntax
const [state, setState] = useState(initialValue);
Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initial state = 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
Key Points
- Returns a pair: current state value & update function
- Update function (
setCount) can accept:
- New value:
setCount(5)
- Function (for previous state):
setCount(prev => prev + 1)
- Triggers re-render when state changes
- Independent state variables for each
useState call
useEffect Hook
Purpose
Handles side effects in functional components (data fetching, subscriptions, manual DOM changes).
Syntax
useEffect(() => {
// Side effect logic
return () => {
// Cleanup (optional)
};
}, [dependencies]); // Dependency array
Example 1: Basic Effect (runs after every render)
useEffect(() => {
document.title = `Clicked ${count} times`;
});
Example 2: With Dependencies (runs only when deps change)
useEffect(() => {
fetchData(userId);
}, [userId]); // Runs only if userId changes
Example 3: Cleanup (e.g., removing event listeners)
useEffect(() => {
const handleResize = () => console.log(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
Dependency Array Rules
| Array | Effect Runs... |
|---|
[] | Once on mount (componentDidMount) |
[dep1, dep2] | When any dependency changes |
| Omitted | After every render |
Important Rules for Hooks
- Only call hooks at the top level (not in loops/conditions)
- Only call hooks from React functions (components/custom hooks)
- Hook order stability: React relies on call order
When to Use Which
| Use Case | Hook |
|---|
| Local state (count, form input) | useState |
| Fetching data on mount | useEffect with [] |
| Syncing state with props/state | useEffect with deps |
| Timer/interval management | useEffect with cleanup |
| Complex state logic | useReducer (advanced) |
Practical Comparison
Class Component (before hooks):
class Counter extends React.Component {
state = { count: 0 };
componentDidMount() { /* side effect */ }
componentDidUpdate() { /* side effect */ }
componentWillUnmount() { /* cleanup */ }
render() { /* UI */ }
}
Function Component (with hooks):
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
// Side effect + cleanup logic here
}, [count]); // Dependencies specified explicitly
return (/* UI */);
}
Key Benefits
- Less boilerplate (no
this binding, lifecycle methods)
- Logic grouping (related code stays together)
- Reusable logic via custom hooks (
useFetch, useLocalStorage)
- Easier testing (hooks are pure functions)
Hooks represent React's modern paradigm—embracing functional programming while retaining React's declarative power. Start with useState/useEffect, then explore others (useContext, useReducer, useCallback, useMemo) as needed.