React Interview Question: When Does useEffect Run?

A
Author
18 Aug, 2026 1 min read 496 views

Short answer: useEffect runs after React has committed the render to the screen. With no dependency array it runs after every render; with [] only after mount; with [a, b] after mount and whenever a or b changed. The cleanup runs before the next effect and on unmount.

useEffect(() => {
  const socket = connect(roomId);
  return () => socket.close();     // cleanup: before re-running and on unmount
}, [roomId]);                       // re-run when roomId changes

useLayoutEffect

Runs synchronously after DOM changes but before the browser paints. Use it only to measure layout and adjust before the user sees a flicker (tooltips, positioning). It blocks painting, so prefer useEffect.

Strict Mode runs effects twice in development

React mounts, unmounts and remounts components in development Strict Mode to reveal effects with missing cleanup. If your effect breaks when run twice, it's missing a cleanup.

You might not need an effect

// Unnecessary: derived state via an effect causes an extra render
const [fullName, setFullName] = useState('');
useEffect(() => setFullName(first + ' ' + last), [first, last]);

// Better: compute during render
const fullName = first + ' ' + last;
  • Compute derived values during render.
  • Handle user actions in event handlers, not effects that watch state.
  • Use effects to synchronise with external systems: subscriptions, timers, non-React widgets, network requests without a data library.

Dependency gotcha

Objects and functions created during render are new every time, so an effect depending on them runs every render. Move them inside the effect, or keep them stable (with useMemo/useCallback, or let React Compiler handle it).

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.