Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 132 ยท Hooks

Effect Dependencies

Learn the useEffect dependency array - what counts as a dependency, omitting vs [] vs listing, stale closures, the exhaustive-deps lint rule and how to remove dependencies properly.

The second argument of useEffect, the dependency array, is the part of effects that causes the most confusion. It looks like a performance setting ("run less often"), but it is really a statement of fact: these are all the reactive values my effect reads. React uses that statement to decide when the effect's code is out of date and must be torn down and set up again.

If you write the array honestly, effects stay correct. If you write it dishonestly, you get stale values, missed updates and bugs that only appear after the user has clicked around for a while. This lesson explains what belongs in the array, shows the stale-closure bug in action, introduces the lint rule that protects you, and then covers the proper ways to remove a dependency when it causes trouble. It continues from Effects with useEffect.

Three forms of the array

There are exactly three things you can pass:

Call When the effect runs
useEffect(fn) After every render
useEffect(fn, []) After the first render only (and once more after unmount cleanup)
useEffect(fn, [a, b]) After the first render, and after any render where a or b changed

"Changed" is decided by comparing each value with its previous one using Object.is: numbers and strings compare by value, objects, arrays and functions by identity. We will come back to that last point.

When each form runs

On mount all three log. Click a: "no array" and "depends on a" log. Click b: only "no array" logs, because b is not in the second effect's array and that effect does not read it. The empty-array effect never logs again. So far this seems simple; the difficulty starts with what you are allowed to leave out.

What counts as a dependency

A reactive value is anything that can change between renders: props, state, and every variable or function declared inside the component body (they are recreated on every render). Rule: every reactive value that your effect's code reads must be listed.

Not dependencies:

  • Values defined outside the component (module-level constants and imports): they never change during rendering.
  • State setter functions from useState and the dispatch of useReducer: React guarantees they are stable.
  • Refs from useRef (the .current property is mutable and is not tracked; see useRef).

Dependencies:

  • Props and state the effect reads.
  • Values calculated from props or state in the body (const url = '/api/' + id).
  • Functions defined in the body that the effect calls.

You do not choose dependencies. They follow from the code: if the effect reads roomId, roomId is a dependency, and the only choice you have is to change the code so that it no longer reads it.

Think of the dependency array as the "reads" list of the effect, the same way that the parameters of a function describe its inputs. You would not call a function with an argument missing and hope it works.

The stale closure bug

Every render creates new functions that close over that render's values. An effect with an incomplete array keeps the closure from an old render, so it keeps reading the old values forever. This is the stale closure bug.

An effect that reads stale state (fails on purpose)

Press the button three times so it shows count = 3, then press a key inside the preview. The console says key a pressed while count is 0. The listener was registered during the first render, so it closed over count from that render, and the empty array promised React there was never a reason to refresh it. The screen shows 3 but the handler believes 0.

The fix is to tell the truth: add count to the array.

JSX
useEffect(() => {
  function handleKeyDown(event) {
    console.log('key ' + event.key + ' pressed while count is ' + count);
  }
  window.addEventListener('keydown', handleKeyDown);
  return () => window.removeEventListener('keydown', handleKeyDown);
}, [count]); // honest

Now each time count changes, React runs the cleanup (removes the old listener, which saw the old count) and the setup (adds a new listener that sees the new count). The cleanup from the previous lesson is what makes this safe: swapping out the listener is cheap and correct.

The linter keeps you honest

You do not have to find these bugs by hand. The react-hooks/exhaustive-deps rule from eslint-plugin-react-hooks (included in every modern React template) reads your effect, works out which reactive values it uses and warns when the array does not match. Treat its warning as a bug report, not a style preference.

TEXT
React Hook useEffect has a missing dependency: 'count'.
Either include it or remove the dependency array.

The tempting "fix" is // eslint-disable-next-line react-hooks/exhaustive-deps. Do not. Suppressing the rule does not change what the code does; it only hides the evidence. The rest of this lesson shows what to do instead: change the code so the dependency is not needed, or accept that the effect should re-synchronize when it changes.

Our live editor does not run ESLint, so lint warnings will not appear in the previews. In a real project, turn the rule on as an error, and see Linting, Formatting and Code Quality.

Removing a dependency properly

If a dependency makes the effect run too often, you cannot simply delete it from the array. You change the effect so that it no longer reads that value. There are four standard techniques.

1. Move the value or function out of the component

If something does not use props or state, it does not need to be inside the component. Moving it to module scope makes it a non-reactive constant, and the dependency disappears.

JSX
// Before: options is recreated every render, so it must be a dependency
function Player() {
  const options = { quality: 'high' };
  useEffect(() => { start(options); }, [options]);
}

// After: a module-level constant is stable
const options = { quality: 'high' };
function Player() {
  useEffect(() => { start(options); }, []);
}

2. Move the function inside the effect

A helper used only by one effect can be declared inside it. Then the effect reads the helper's own inputs, not the helper:

JSX
useEffect(() => {
  function createGreeting() {
    return `Hello, ${name}!`;
  }
  console.log(createGreeting());
}, [name]); // only name matters

3. Derive values instead of storing them

If a dependency is a state variable you could calculate from a prop, compute it in render and depend on the smaller input. Choosing a State Structure explains the idea; here it removes whole chains of "update this when that changes" effects.

4. Use a functional update

When an effect reads state only to compute the next state, pass an updater to the setter. The effect then no longer reads the state.

A ticker that does not depend on its own state

The interval is created once per start, not once per tick. If the effect had read count directly (setCount(count + 1)), count would be a dependency and the interval would be torn down and rebuilt on every tick, losing time and adding needless work. Start it, wait a moment and the label changes from zero; the log shows one timer started and, after stopping, one timer stopped.

When none of these techniques fit, because you genuinely need the latest value inside an effect without re-running it, React has a dedicated tool, useEffectEvent.

Objects and functions as dependencies

Because dependencies compare with Object.is, an object or function created inside the component is a new value on every render, even if its content is identical. Putting it in the array makes the effect run after every render.

A new object every render

Press "Re-render" twice. effect with primitive deps ran appears only once, at mount. effect with object dep ran appears three times: at mount and after each unrelated re-render, because options is a different object every time even though query never changed. For an effect that opens a network connection, that means a new connection per render.

Ways out, in order of preference:

  1. Depend on the primitives. Read query and limit inside the effect and list those.
  2. Create the object inside the effect so it is not a dependency at all: const options = { query, limit: 10 }; within the effect body.
  3. Hoist it to module scope if it never changes.
  4. Memoize it with useMemo/useCallback (useMemo and useCallback) when it must be passed in from outside, but this is a last resort.

The same goes for functions passed as props: if a parent creates onResult={() => ...} inline, a child effect that lists onResult will rerun every render. Don't suppress it; either make the parent's function stable, or in the child read the latest callback through an effect event.

An infinite loop

Setting state inside an effect that depends on that state, or on something derived from a new object each render, causes a loop: render, effect, set state, render, effect, and so on. React will show a "Maximum update depth exceeded" error eventually.

JSX
// Infinite loop: the effect sets state, which re-renders, which creates a new array...
function Broken({ items }) {
  const [sorted, setSorted] = useState([]);
  useEffect(() => {
    setSorted([...items].sort());
  }, [items, sorted]); // sorted changes on every run
}

// Better: derive in render, no effect or extra state at all
function Fixed({ items }) {
  const sorted = [...items].sort();
  return <ul>{sorted.map((item) => <li key={item}>{item}</li>)}</ul>;
}

If you find yourself writing setX in an effect, read You Might Not Need an Effect first.

Putting it together: a data subscription

Here is a complete effect with honest dependencies that re-synchronizes when its input changes. A fake "server" delivers messages for a topic after a short delay; the effect subscribes to the current topic and cleans up when the topic changes.

Re-subscribing when the topic changes

Switch topics and the log reads unsubscribe: weather, subscribe: sports. The effect reads topic and setMessage only; setMessage is stable, so [topic] is the complete, honest array. The reset to "waiting..." happens inside the effect here for brevity, but remember that resetting state on identity change is often neater with a key on <Feed key={topic} />.

Cheat sheet

  • List every reactive value the effect reads. The linter will tell you which.
  • Empty array means "the effect reads nothing reactive". If it does, the array is wrong.
  • No array means "run after every render", which is occasionally correct (rare, usually for syncing a ref or measuring).
  • Too many re-runs? Change the code, not the array: move things out, move them in, derive, or use updater functions.
  • Objects and functions created in render are new each time; depend on their primitive inputs instead.
  • Never suppress the lint rule to silence a warning.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an empty dependency array [] promise?

    An empty array says the effect uses no props, state or other render-scoped values. If the effect does read some, you get stale values.
  2. 2. Which of these is NOT a dependency that needs listing?

    State setters and dispatch functions are guaranteed stable by React. Props, state and functions or values declared in the component body are reactive.
  3. 3. An effect with [] adds a keydown listener that logs count. After the count reaches 3 the log still says 0. What is this bug called?

    The listener closed over count from the first render and was never refreshed because the array hid the dependency.
  4. 4. An effect depends on an options object created in the component body. What happens?

    Dependencies are compared with Object.is. A fresh object has a new identity on each render, so the effect re-runs. Depend on the primitive values instead.
  5. 5. An interval effect calls setCount(count + 1), so count must be a dependency and the interval restarts every tick. What is the best fix?

    With an updater function the effect no longer reads count, so the dependency disappears honestly and the interval is created only once.

Summary

  • The dependency array lists every reactive value (props, state and anything declared in the component body) that the effect reads; it is derived from the code, not chosen.
  • No array runs after every render, [] runs on mount only, and [a, b] runs when a or b changes by Object.is.
  • Leaving dependencies out causes stale closures: the effect keeps using values from an old render.
  • Use the exhaustive-deps lint rule and never suppress it; remove dependencies by changing the code.
  • Remove dependencies by moving values outside, moving functions inside the effect, deriving values, or using functional state updates.
  • Objects and functions created during render change identity every time; depend on primitives or create them inside the effect.

Next: Cleanup, Subscriptions and Timers