How does the useEffect dependency array work?
What the dependency array controls
The dependency array describes the reactive values an effect reads. After a component commits, React compares each dependency with its previous value using Object.is. If one changes, React cleans up the previous synchronization and starts the new one. Include every prop, state value, and component-local variable or function read by setup or cleanup; dependencies describe the code, rather than a schedule you choose independently.
| Form | Behavior after commit |
|---|---|
| No second argument | Setup after the initial commit and every subsequent commit; cleanup before each new setup |
[] | No dependency-driven reruns during the same mount; cleanup on removal |
[roomId] | Initial setup, then cleanup and setup when roomId changes |
An empty array does not guarantee one lifetime execution. Remounting creates a fresh effect. With Strict Mode enabled at the root, development performs an extra setup → cleanup → setup check. This catches missing cleanup; production does not perform that development check. Effects do not run during server rendering.
Follow one setup and cleanup cycle
import { useEffect } from 'react';function RoomStatus({ roomId }) {useEffect(() => {const handler = event => console.log(roomId, event.detail);window.addEventListener('room-message', handler);return () => window.removeEventListener('room-message', handler);}, [roomId]);return <p>Listening in room {roomId}</p>;}
For room A, setup registers A's handler. Switching to B removes A's handler before registering B's. Removing the component removes B's handler. Cleanup closes over the old values: it must undo the subscription that setup actually created. A rerender with the same room ID does not resubscribe.
Diagnose a stale closure
// Problem: the callback captures count from the first render.useEffect(() => {const timer = setInterval(() => setCount(count + 1), 1000);return () => clearInterval(timer);}, []);// Correction: an updater reads the latest pending state.useEffect(() => {const timer = setInterval(() => setCount(c => c + 1), 1000);return () => clearInterval(timer);}, []);
The problem version repeatedly requests the same next value. The corrected callback no longer reads count, so it does not require that dependency. Adding [count] also updates the closure, but recreates the interval each time. If the callback reads another changing value, such as a step prop, include it or restructure the synchronization. Do not suppress the dependency lint rule to force an empty array.
Object and function identity
// Problem: options and load are new references on each render.const options = { userId };const load = () => fetch(`/api/users/${options.userId}`);useEffect(() => { load(); }, [load]);// Correction: create request details inside the effect.useEffect(() => {const controller = new AbortController();async function load() {try {const response = await fetch(`/api/users/${userId}`, {signal: controller.signal,});if (!response.ok) throw new Error(`HTTP ${response.status}`);await response.json();} catch (error) {if (!controller.signal.aborted) console.error(error);}}void load();return () => controller.abort();}, [userId]);
These are contrasting excerpts inside a component. Objects and functions compare by identity; identical contents do not make a newly created reference equal. Prefer moving construction inside the effect or outside the component when appropriate. Memoization is useful when reference stability is needed elsewhere, but is not the first fix for every dependency problem.
Requests: cancel work and ignore stale results
import { useEffect, useState } from 'react';export function Profile({ userId }) {const [view, setView] = useState({ status: 'loading', user: null });useEffect(() => {let active = true;const controller = new AbortController();setView({ status: 'loading', user: null });async function load() {try {const response = await fetch(`/api/users/${userId}`, {signal: controller.signal,});if (!response.ok) throw new Error(`HTTP ${response.status}`);const user = await response.json();if (active) setView({ status: user ? 'success' : 'empty', user });} catch (error) {if (active && !controller.signal.aborted) {console.error('Profile request failed', error);setView({ status: 'error', user: null });}}}void load();return () => { active = false; controller.abort(); };}, [userId]);if (view.status === 'loading') return <p>Loading profile…</p>;if (view.status === 'error') return <p role="alert">Unable to load profile.</p>;if (view.status === 'empty') return <p>No profile found.</p>;return <p>{view.user.name}</p>;}
This example assumes an endpoint returning a user object or null. Aborting avoids unnecessary fetch work; the active guard also prevents already completed or non-cancelable work from publishing old results after cleanup. A 404/500 requires an explicit response.ok check. JSON parsing can fail too. Expected cleanup cancellation should not produce an error banner. A framework loader or query library is often preferable for caching, deduplication, and loading ownership; this example isolates the lifecycle mechanics.
Can this be solved without an effect?
Compute derived values during render: const total = items.reduce((sum, item) => sum + item.price, 0). A purchase caused by a click belongs in the click handler, rather than an effect watching a boolean. Use an effect for an external synchronization, such as a subscription, timer, or browser API. Updating a dependency inside its own effect can create a loop; first question whether that state needs to exist.
Interview follow-ups
- Why did this effect rerun: a primitive change or a new object/function reference?
- What resource does cleanup undo, and which render's values does it capture?
- What happens if request A resolves after request B?
- Can a derived value or an event handler replace this effect?
Reviewed 1 October 2026 against React useEffect and You might not need an effect.
Debug an effect step by step
Trace one synchronization before changing the dependency array.
- Identify each reactive value read by setup and cleanup.
- Check Object.is comparisons, including fresh object and function identities.
- Confirm cleanup undoes the old resource and blocks obsolete results.
- Decide whether rendering or an event handler can replace the effect.
Related interview practice
Related React Ecosystem interview topics
Continue with nearby questions from the same topic cluster.