useEffect, useMemo and rendering lists
Use effects only for syncing with the outside world, memoise only real costs, and give list items stable keys.
Effects, memoisation and keys are where candidates who learned React by copying snippets tend to slip. Each has a narrow purpose, and screenings test whether you know it.
What useEffect is for
An effect synchronises your component with something outside React: a network request, a timer, a subscription, or the document title. It runs after the render is on screen. The dependency array controls when it re-runs:
- No array: after every render.
[]: after the first render only.[userId]: after the first render and wheneveruserIdchanges.
List every value from the component that the effect reads. Leaving one out gives you stale data that is hard to trace.
Always clean up
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);The returned function runs before the effect re-runs and on unmount. In development Strict Mode, React mounts components twice on purpose to reveal missing cleanup. If something breaks then, the cleanup is the fix.
Do not use effects to compute values from props or state. If fullName is first + ' ' + last, calculate it during render instead of storing it in state.
useMemo with purpose
useMemo(() => filterProducts(list, term), [list, term]) skips the calculation when list and term are unchanged. It helps with genuinely expensive work or when a stable object is passed to a memoised child. It does not stop the component from rendering, and wrapping every small calculation adds complexity for no gain.
Keys in lists
When rendering with map, each item needs a key that is unique among siblings and stable over time, usually an id from the data. Index keys work only for lists that never reorder, insert or delete. Otherwise state such as an open panel or typed text can attach to the wrong row.
Rules of hooks
- Call hooks only at the top level of a component or custom hook.
- Never call them inside conditions, loops or nested functions.
- Keep the call order the same on every render.
Checklist: for each effect, can you name the outside system it syncs with and the cleanup it needs? If not, it may not need to be an effect.
More in Web and app