What is useEffect in React?
Learn what useEffect does in React, how the dependency array controls re-runs, why cleanup functions matter, and how it replaces class lifecycle methods.
Expected Interview Answer
useEffect is a React hook that lets a function component run side effects — such as fetching data, subscribing to events, or manually touching the DOM — after render, synchronizing the component with something outside React's own rendering system.
You call useEffect with a function containing the side effect and an optional dependency array; React runs the effect after the DOM has been updated, and re-runs it only when a value in the dependency array changes. An empty dependency array means the effect runs once after the initial render, while omitting the array entirely re-runs it after every render. If the effect function returns a cleanup function, React calls that cleanup before the next effect run and when the component unmounts, which is essential for canceling subscriptions or timers. useEffect replaces the combined behavior of componentDidMount, componentDidUpdate, and componentWillUnmount from class components in a single, more composable API.
- Synchronizes components with external systems
- Runs code after the DOM is updated
- Dependency array controls when it re-runs
- Built-in cleanup prevents memory leaks
- Replaces multiple class lifecycle methods with one hook
AI Mentor Explanation
useEffect is like the ground staff who step onto the pitch only after an over finishes, never mid-delivery, to water the pitch or replace the covers. They check a checklist (the dependency array) to decide whether anything actually needs attention this over, and they always tidy up their equipment (cleanup) before the next over begins.
Step-by-Step Explanation
Step 1
Import useEffect
Import useEffect from 'react' alongside any other hooks you need.
Step 2
Call it with a function
Pass a function containing the side effect logic as the first argument.
Step 3
Add a dependency array
Pass an array of values as the second argument; the effect re-runs only when one of them changes.
Step 4
Return a cleanup function
Optionally return a function from the effect to cancel subscriptions, timers, or listeners.
Step 5
React schedules execution
React runs the effect after committing changes to the DOM, not during render.
What Interviewer Expects
- Explains useEffect runs after render/DOM update
- Knows the dependency array controls re-execution
- Understands the cleanup function's purpose
- Can compare empty array vs no array vs populated array
- Relates it to replacing lifecycle methods
Common Mistakes
- Omitting the dependency array causing infinite re-render loops
- Forgetting to clean up subscriptions or timers
- Treating useEffect as running before the DOM updates
- Adding unnecessary values to the dependency array
- Using useEffect for logic that should be computed during render
Best Answer (HR Friendly)
“useEffect lets a component do things outside of just displaying information, like fetching data from a server or setting a timer, after it finishes showing on screen. It also handles cleaning up after itself so the app doesn't slow down or leak resources over time.”
Code Example
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let cancelled = false;
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => {
if (!cancelled) setUser(data);
});
return () => {
cancelled = true; // cleanup avoids setting state after unmount
};
}, [userId]); // re-run only when userId changes
return <p>{user ? user.name : 'Loading...'}</p>;
}Follow-up Questions
- When does the dependency array cause an effect to re-run?
- Why is a cleanup function important in useEffect?
- What is the difference between useEffect and useLayoutEffect?
- What happens if you omit the dependency array entirely?
- How do you avoid stale closures inside useEffect?
MCQ Practice
1. When does React run a useEffect callback?
useEffect runs after React commits changes to the DOM, making it safe for side effects that read the updated UI.
2. What does an empty dependency array ([]) mean for useEffect?
An empty dependency array tells React the effect has no reactive values, so it runs only once after mount.
3. What is the purpose of a function returned from useEffect?
A returned function is treated as cleanup logic, run before the next effect and on unmount.
Flash Cards
What does useEffect do? — It runs side effects, like data fetching or subscriptions, after the component renders.
What controls when useEffect re-runs? — The dependency array passed as its second argument.
How do you clean up an effect? — Return a function from the effect callback; React calls it before the next run and on unmount.
What class lifecycle methods does useEffect replace? — componentDidMount, componentDidUpdate, and componentWillUnmount combined.