What is the useEffect Hook in React?
Learn what the useEffect Hook does in React: side effects, the dependency array, cleanup functions, and data fetching, with code and interview questions.
Expected Interview Answer
useEffect is a React Hook that lets you run side effects — like data fetching, subscriptions, timers, or manually touching the DOM — after a component renders, and optionally clean them up.
You pass a function and a dependency array: useEffect(() => { ... }, [deps]). React runs the effect after paint, and re-runs it whenever a value in the dependency array changes. An empty array [] runs it once on mount; omitting the array runs it after every render. If the effect returns a function, React calls that cleanup before the next run and on unmount, which is how you clear timers, unsubscribe, or abort requests.
- Synchronizes a component with external systems
- Handles data fetching and subscriptions declaratively
- Cleanup function prevents memory leaks
- Dependency array gives precise control over when effects run
- Keeps side effects out of the render phase
AI Mentor Explanation
useEffect is like the drinks break that only happens after an over is bowled, never during a delivery. The dependency array is the trigger — a wicket falling or an over completing — that decides when the break runs. The cleanup is clearing the field of drinks trolleys before play resumes, just as an effect tears down before the next run.
Step-by-Step Explanation
Step 1
Import useEffect
Bring in useEffect from React alongside your other Hooks.
Step 2
Call it with an effect function
Pass a function containing the side effect you want to run after render.
Step 3
Add a dependency array
List the values the effect depends on so React knows when to re-run it.
Step 4
Return a cleanup function
If the effect creates a subscription or timer, return a function to tear it down.
Step 5
Reason about timing
Remember effects run after paint, and cleanup runs before the next run and on unmount.
What Interviewer Expects
- Understanding that effects run after render, not during it
- How the dependency array controls when the effect re-runs
- The role of the cleanup function in preventing leaks
- Difference between [], [deps], and no array
- Awareness of common pitfalls like missing dependencies and infinite loops
Common Mistakes
- Omitting the dependency array and causing effects to run every render
- Missing dependencies that lead to stale values inside the effect
- Forgetting the cleanup function and leaking timers or subscriptions
- Updating state unconditionally inside an effect, causing an infinite loop
- Using an async function directly as the effect callback instead of calling one inside
Best Answer (HR Friendly)
“useEffect is a tool in React for running tasks that happen alongside the display, like loading data or setting up a timer, after the component appears. It can also clean up after itself so nothing keeps running when it should not.”
Code Example
import { useState, useEffect } from 'react'
function UserProfile({ userId }) {
const [user, setUser] = useState(null)
useEffect(() => {
const controller = new AbortController()
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(res => res.json())
.then(setUser)
.catch(err => {
if (err.name !== 'AbortError') console.error(err)
})
return () => controller.abort()
}, [userId])
return <p>{user ? user.name : 'Loading...'}</p>
}Follow-up Questions
- What is the difference between passing [], [deps], and no dependency array?
- How do you clean up a subscription or timer in useEffect?
- Why can a missing dependency cause a stale value?
- How do you avoid an infinite loop inside useEffect?
- When would you use useLayoutEffect instead of useEffect?
MCQ Practice
1. When does an effect with an empty dependency array [] run?
An empty dependency array tells React the effect has no dependencies, so it runs once after mount.
2. What is the purpose of the function returned from an effect?
A returned cleanup function lets React tear down subscriptions, timers, or requests before re-running or unmounting.
3. What causes an effect to re-run?
React compares dependency values between renders and re-runs the effect only when one has changed.
Flash Cards
When do effects run relative to render? — After the component renders and the browser paints, not during render.
What does an empty dependency array mean? — The effect runs only once, after the initial mount.
What does the returned function do? — It is the cleanup, run before the next effect and when the component unmounts.
How do you avoid an infinite loop? — Make sure the dependency array is correct and don't unconditionally set state the effect depends on.