Concept
Effects (useEffect)
Syncing a component with things outside React, and cleaning up afterwards.
Effects explained
An effect in React is code that keeps a component in sync with something outside React: a subscription, a timer, a network connection, the document title or a third-party widget. You write it with useEffect; React runs it after the component renders and runs its cleanup before the effect runs again or when the component leaves the screen.
How useEffect works
useEffect(() => {
const conn = createConnection(roomId); // set up
conn.connect();
return () => conn.disconnect(); // clean up
}, [roomId]); // re-run when roomId changes
- No dependency array: runs after every render.
- Empty array
[]: runs once after the first render, cleans up on unmount. [a, b]: runs again wheneveraorbchanges. List every value from the component that the effect reads.
When you do not need an effect
- Derived data: compute it during render instead of copying it into state from an effect.
- Responding to a user event: do it in the event handler, where you know what happened.
- Resetting state when a prop changes: give the component a
keyso React creates a fresh instance.
Common mistakes
- Missing dependencies, so the effect keeps using old values.
- Objects or functions as dependencies that are recreated every render, making the effect run every time.
- No cleanup for subscriptions and timers, which leaks memory and duplicates work.
- Fetching without handling races: if the input changes quickly, an older response can arrive last. Ignore stale results in the cleanup.
- Surprise double runs in development: Strict Mode mounts components twice to expose missing cleanup. Production runs once.
What interviewers ask about effects
- "What does the dependency array do?" Tells React when to re-run the effect.
- "Why does my effect run twice?" Strict Mode in development.
- "Fix this effect that loops forever." It sets state that is also a dependency, or depends on a new object each render.
What should you learn before Effects?
- FunctionsReusable blocks of code; in JavaScript they are values that can be passed around and returned.
- PropsInputs passed from a parent component to a child.
- Variables and scopeWhere a variable can be read: global, function and block scope, and how let, const and var differ.
- ClosuresA function that keeps access to the variables of the scope it was created in, after that scope has finished.
- StateData that changes over time and makes the UI re-render, and where to keep it.
- React hooksFunctions such as useState and useEffect that add state and lifecycle to function components.
What to learn after Effects
- Data fetchingLoading data for a UI: where requests start, caching, and loading and error states.
Connections to other concepts
- Related
- Strict Mode
Practise Effects
- Intermediate React Interview Questions4 questions on Effects
- React Interview Questions for Freshers1 question on Effects