We are going to explain React Hooks in a structured way.
Steps:
- What are React Hooks?
- What problem did Hooks solve?
- What is the
useState hook? Example.
- What is the
useEffect hook? Example.
- What are the "Rules of Hooks"?
Let's break it down.
React Hooks
What Are React Hooks?
React Hooks are special functions introduced in React 16.8 (2019) that allow you to use state and other React features without writing a class component. They let you "hook into" React's state and lifecycle features from function components.
Problem Hooks Solved
Before Hooks, React had two major patterns:
- Function Components (stateless): Could only receive props and render UI. Had no lifecycle methods or internal state.
- Class Components (stateful): Had state (
this.state) and lifecycle methods (componentDidMount, etc.), but came with problems:
Problems with Class Components:
- 🔄
this binding confusion: Required binding event handlers or using arrow functions.
- 📦 Code scattering: Related logic split across multiple lifecycle methods (e.g.,
componentDidMount + componentDidUpdate + componentWillUnmount).
- 🧩 Complex patterns: Required HOCs (Higher-Order Components) or render props for logic reuse, causing "wrapper hell."
- 🗑️ Boilerplate: More code for simple components.
Hooks Fixed This By:
- ✅ Allowing state in function components.
- ✅ Letting side effects be organized by what they do, not when they run.
- ✅ Enabling custom hooks for reusable logic without HOCs.
- ✅ Reducing component complexity.
useState Hook
What it does: Adds local state to function components.
Returns: An array with two elements:
- Current state value
- Function to update that state (like
setState but replaces, not merges)
Example:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable "count" with initial value 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Key Points:
- State updates trigger re-renders.
- State is isolated per component.
setCount replaces the old value (unlike class setState which merges).
useEffect Hook
What it does: Handles side effects (data fetching, subscriptions, DOM manipulation) in function components. Unifies componentDidMount, componentDidUpdate, and componentWillUnmount.
Syntax:
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup (optional)
};
}, [dependencies]); // Dependency array
Example 1: Run on mount/unmount (no dependencies):
useEffect(() => {
console.log('Component mounted');
return () => {
console.log('Component will unmount');
};
}, []); // Empty array = run once on mount
Example 2: Run when dependency changes:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Re-run when "count" changes
Example 3: Data fetching:
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(data => setData(data));
}, []); // Fetch once on mount
Rules of Hooks
Hooks have two essential rules enforced by ESLint plugin (eslint-plugin-react-hooks):
1. Only Call Hooks at the Top Level
- ✅ Do: Call hooks inside function components or custom hooks.
- ❌ Don't: Call hooks inside loops, conditions, or nested functions.
Why? React relies on call order to track state. If hooks run conditionally, order changes between renders → bugs.
Bad Example:
if (condition) {
const [state, setState] = useState(); // ❌ Violates rule
}
2. Only Call Hooks from React Functions
- ✅ Do: Call hooks from:
- React function components
- Custom hooks (functions starting with
use)
- ❌ Don't: Call hooks from regular JavaScript functions, class components, or event handlers.
Why? Hooks need React's internal context to work.
Bad Example:
function regularFunction() {
const [state, setState] = useState(); // ❌ Not a React function
}
Quick Summary Table
| Feature | Class Component | Hook Equivalent |
|---|
| State | this.state / this.setState | useState |
| Lifecycle | componentDidMount etc. | useEffect |
| Context | static contextType / Context.Consumer | useContext |
| Refs | createRef() / ref attribute | useRef |
| Performance | shouldComponentUpdate | useMemo / useCallback |
Why Hooks Matter Today
- 🚀 Simpler code: Fewer lines, easier to read.
- 🔁 Reusable logic: Custom hooks (e.g.,
useFetch, useLocalStorage).
- 📦 Tree-shakable: Smaller bundle sizes vs. HOCs.
- 🧪 Easier testing: No
this mocking; hooks can be tested in isolation.
Most React codebases today use Hooks exclusively. Classes are still supported but discouraged for new code.