🪝 Basic Hooks
Rules of Hooks, useState patterns, useEffect dependency array, and cleanup functions.
Rules of Hooks
Two foundational rules required when using React Hooks.
Note: 1. Call Hooks only at top level (not inside loops or conditions). 2. Call Hooks only from React function components or custom Hooks.
Mastering useEffect Hook
The `useEffect` hook performs side effects (API calls, subscriptions, DOM mutations) in function components.
| Dependency Array | Effect Execution Timing |
|---|---|
| No Array (undefined) | Runs after EVERY single render. |
| Empty Array ([]) | Runs ONCE after initial component mount. |
| With Dependencies ([id]) | Runs on mount AND whenever `id` value changes. |
Effect Cleanup Functions
Return a cleanup function from `useEffect` to clear subscriptions, intervals, or event listeners when components unmount.
Timer.jsx
JSX
import { useState, useEffect } from 'react'; export function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setSeconds(prev => prev + 1); }, 1000); // Cleanup function on unmount return () => clearInterval(intervalId); }, []); return <h3>Elapsed Time: {seconds}s</h3>; }