Skip to the page

Effects and synchronisation · core

useEffect: synchronising with the outside world

useEffect runs code after React commits, to keep a component in sync with a system outside React (a socket, a timer, a browser API); its cleanup runs before the next run and on unmount.

The notes

What you must know

  • Effects are for synchronising with external systems: subscriptions, timers, the DOM outside React, third-party widgets, analytics on view. They are not for calculating data or reacting to user events.
  • Timing: effects run after the commit, usually after the browser paints. They do not run on the server.
  • Dependencies: [] = after the first commit (plus StrictMode's extra mount in development); [a, b] = when a or b changed by Object.is; no array = after every commit.
  • Cleanup runs before the effect runs again with new deps, and when the component unmounts. Think "start sync / stop sync", not "mount / unmount".
  • An IIFE in the component body runs during every render, on the server too, and before the DOM exists. That is why it is not the same as useEffect(..., []).
  • Lifecycle mapping is approximate: componentDidMount ~ effect with []; componentWillUnmount ~ cleanup; shouldComponentUpdate ~ memo. Error boundaries and getSnapshotBeforeUpdate still need classes.
  • Order of a change: render, commit, layout effects (cleanup old then run new), paint, passive effect cleanups (old), passive effects (new).

The red pen

Common traps: mistake → fix

  • Mistake: "[] means it runs once ever"

    Fix: once per mount; in development StrictMode it mounts, unmounts and mounts again; <Activity> hide/show also re-runs it.

  • Mistake: "useEffect is how you respond to state changes"

    Fix: respond to events in the event handler; calculate derived values in render.

  • Mistake: "An IIFE in the body is the same as an effect with []"

    Fix: it runs every render, during render, and on the server.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is useEffect for?
  2. Does useEffect(fn, []) do the same thing as an IIFE in the component body?
  3. When exactly does the cleanup function run?
  4. What happens if you put an object or array literal in the deps?
  5. Do effects run during server rendering?

Practise

Practise with these questions

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