Skip to the page

Hooks & effects · Write code

Fix an infinite useEffect loop

The interviewer asks

This page hammers our API and freezes. Find the bug.

function Products({ category }) {
  const [items, setItems] = useState([]);
  const filters = { category, inStock: true };
  useEffect(() => {
    fetchProducts(filters).then(setItems);
  }, [filters]);
  return <List items={items} />;
}

Then

Follow-ups the interviewer asks next

  1. Fix it without useMemo.
  2. What if filters comes from props created by the parent?
  3. What if the effect sets state that's also a dependency?
  4. How would TanStack Query or RTK Query structure this instead?

The answer

What a strong answer covers

  • The object literal gets a new identity each render. The effect fetches, sets state, re-renders, and the new filters re-fires the effect.
  • Fix: depend on primitives ([category]), build the object inside the effect, or memoize at the source.
  • Never set state from a value derived in the effect when you could compute it in render.
  • Query libraries key on serialisable query keys.

The red pen

Common traps

Avoid:// eslint-disable-next-line; using JSON.stringify(filters) as a dependency without understanding why.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

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

Start your free interview