useEffect
Subject: React
π What is useEffect?
useEffect is a React Hook that lets you run side effects in your functional components.
A βside effectβ is anything that happens outside the component during rendering β like fetching data, setting up timers, updating the DOM, or cleaning up resources.
π§ Why Do We Need It?
Functional components donβt have lifecycle methods like componentDidMount or componentDidUpdate. So React gives us useEffect to handle:
| Purpose | Example | 
|---|---|
| Fetch data | Get users from API | 
| Set up a timer | setInterval() or setTimeout() | 
| DOM updates | Change document title | 
| Cleanup on unmount | Clear timers, remove listeners | 
β Syntax
| Part | Meaning | 
|---|---|
useEffect(() => {}) | Run after component renders | 
return () => {} | Cleanup function (runs before unmount or update) | 
[dependencies] | When to re-run the effect | 
β Example 1: Run Once on Mount
π Empty array [] = run once when component mounts.
β Example 2: Run on State Change
π Runs every time count changes.
β Example 3: Cleanup on Unmount
π Return function inside useEffect handles cleanup.
β οΈ Common Mistakes
| Mistake | Correct Way | 
|---|---|
| Missing dependency | Add to [] to avoid stale data or infinite loops | 
| Forgetting cleanup | Always clear timers, event listeners, etc. | 
| Direct DOM manipulation | Prefer React state unless absolutely necessary | 
π Dependency Array Rules
| Dependency Array | What Happens | 
|---|---|
[] | Run once on mount | 
[count] | Run when count changes | 
| No array | Run on every render (β οΈ not optimal) | 
[a, b] | Run when either a or b changes | 
π Summary Table
| Feature | Description | 
|---|---|
useEffect() | Run side effects in functional components | 
[] dependency | Run once when mounted | 
[state] dependency | Re-run effect on state/prop change | 
| Cleanup function | Clear intervals, subscriptions, etc. on unmount | 
| Common uses | Fetching API, timers, title update, event binding | 
β Real-Life Examples
| Example | useEffect Logic | 
|---|---|
| Fetch users from API | On mount β fetch() β update state | 
| Page title update | Whenever title prop changes | 
| Input validation | Watch input β re-run validation logic | 
| Auto logout timer | Start timer β cleanup on logout/unmount | 
Advertisement Slot 1
Advertisement Slot 2