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:

PurposeExample
Fetch dataGet users from API
Set up a timersetInterval() or setTimeout()
DOM updatesChange document title
Cleanup on unmountClear timers, remove listeners

βœ… Syntax

PartMeaning
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

MistakeCorrect Way
Missing dependencyAdd to [] to avoid stale data or infinite loops
Forgetting cleanupAlways clear timers, event listeners, etc.
Direct DOM manipulationPrefer React state unless absolutely necessary

πŸ” Dependency Array Rules

Dependency ArrayWhat Happens
[]Run once on mount
[count]Run when count changes
No arrayRun on every render (⚠️ not optimal)
[a, b]Run when either a or b changes

πŸ“Œ Summary Table

FeatureDescription
useEffect()Run side effects in functional components
[] dependencyRun once when mounted
[state] dependencyRe-run effect on state/prop change
Cleanup functionClear intervals, subscriptions, etc. on unmount
Common usesFetching API, timers, title update, event binding

βœ… Real-Life Examples

ExampleuseEffect Logic
Fetch users from APIOn mount β†’ fetch() β†’ update state
Page title updateWhenever title prop changes
Input validationWatch input β†’ re-run validation logic
Auto logout timerStart timer β†’ cleanup on logout/unmount

πŸ‘‰ Next: Explore useContext ➑️