Introduced in React 16.8, Hooks are functions that let you "hook into" React state and lifecycle features directly from functional components.
Before hooks, functional components were stateless presentation templates. Hooks eliminated the need for complex Class Component syntax, this binding confusion, and fragmented lifecycle methods.
To guarantee that hooks execute in the exact same order on every component render, you must strictly follow the Rules of Hooks:
flowchart TD
Rules["Rules of Hooks"] --> Rule1["1. Call Hooks ONLY at Top Level (Never inside loops, conditions, or nested functions)"]
Rules --> Rule2["2. Call Hooks ONLY from React Function Components or Custom Hooks"]
| Category | Built-in Hook | Purpose |
|---|---|---|
| State Hooks | useState |
Declares local reactive state variable |
useReducer |
Manages complex state updates via action dispatching | |
| Effect Hooks | useEffect |
Synchronizes component with external APIs / side effects |
useLayoutEffect |
Fires synchronously before browser screen repaint | |
| Ref Hooks | useRef |
Holds persistent mutable references / DOM node access |
| Context Hook | useContext |
Reads global React Context values |
| Performance Hooks | useMemo |
Caches computed calculation results |
useCallback |
Memoizes event handler function references |
// ❌ WRONG: Calling Hook inside a conditional branch
function BadComponent({ isAuthorized }) {
if (isAuthorized) {
const [secret, setSecret] = useState(''); // VIOLATION!
}
return <div>Bad Pattern</div>;
}
// ✅ CORRECT: Top-level Hook declaration
function GoodComponent({ isAuthorized }) {
const [secret, setSecret] = useState('');
if (!isAuthorized) {
return <div>Unauthorized</div>;
}
return <div>Secret: {secret}</div>;
}
Explain why calling a hook inside an if condition breaks React's internal state tracking across re-renders.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.