Skip to the page

Effects and synchronisation · mid

Dependencies, object identity and infinite loops

React compares each dependency with Object.is, so an object, array or function created during render is "new" every time and re-runs the effect; if that effect sets state, you get an infinite loop.

The notes

What you must know

  • Classic loop: const filters = { category } in render + useEffect(() => fetch(filters).then(setItems), [filters]) -> fetch, setState, re-render, new filters, fetch again, forever.
  • Fix by depending on primitives ([category]) and building the object inside the effect. Or move the object outside the component if it is constant. Or memoize it at the source.
  • Functions are objects too: a function declared in render is new every time. Move it inside the effect, outside the component, or wrap it in useCallback.
  • Never "fix" a loop by removing deps or silencing react-hooks/exhaustive-deps; that creates stale-data bugs instead.
  • Setting state that is also a dependency (setCount(count + 1) in an effect depending on count) loops; use the updater form or rethink whether you need the effect.
  • React Compiler lint rules (set-state-in-effect, set-state-in-render) in eslint-plugin-react-hooks flag many of these patterns.
  • JSON.stringify(obj) as a dependency works for small plain data but hides the real problem and costs time every render.

The red pen

Common traps: mistake → fix

  • Mistake: "Add // eslint-disable-next-line to stop the loop"

    Fix: it hides a missing or unstable dependency.

  • Mistake: "Deep comparison of deps would be better"

    Fix: React deliberately uses Object.is; stabilise the value instead.

  • Mistake: "useMemo is the only fix"

    Fix: usually the better fix is depending on primitives or moving the object into the effect.

Easy to hard

Questions interviewers ask, easy to hard

  1. This page hammers our API and freezes. Find the bug. (object literal in deps)
  2. Fix it without useMemo.
  3. What if filters is a prop created by the parent?
  4. How would TanStack Query or RTK Query structure this instead?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview