React useEffect Hooks
🔥 React useEffect Hook
The useEffect Hook allows you to perform side effects in functional components.
📌 A side effect is anything that happens outside the normal UI rendering, such as:
Fetching API data
Using
setTimeoutorsetIntervalUpdating the document title
Working with browser storage
Adding event listeners
Before Hooks, these tasks were done in class lifecycle methods:
| Class Component | Equivalent with Hooks |
|---|---|
componentDidMount() | useEffect(() => {}, []) |
componentDidUpdate() | useEffect(() => {}) |
componentWillUnmount() | Cleanup inside effect |
🧪 Basic Example
📍 This effect runs after every render, including state changes.
🎯 Run Effect Only Once (Like componentDidMount)
Add an empty dependency array []:
Useful for:
✔ Fetching data
✔ Setting up listeners
✔ Initial setup logic
🎯 Run Effect Only When Specific Value Changes
➡ This runs the effect only when count changes, not on every render.
🧹 Cleanup Function (Unmount Logic)
Use cleanup to remove timers, listeners, etc.
➡ Executes when component unmounts or before re-running effect.
Example: Timer with Cleanup
🌐 Fetch API Example
⚠️ Rules & Notes
| Rule | Explanation |
|---|---|
| Must be called at top level | No loops, conditions, or nested functions |
| Runs after render | React first paints UI, then runs effect |
| Cleanup prevents memory leaks | Required when using timers/listeners |
🔍 Summary Table
| Dependency | When Effect Runs |
|---|---|
| No array | After every render |
[] empty array | Only once (on mount) |
[value] | Only when value changes |
| Cleanup return function | On unmount or before next run |
