Effect Queue — React

Understand useEffect: 5 levels predicting fire and cleanup counts from dep arrays, no deps, the object identity trap and StrictMode double-invoke.

What you learn in this game

useEffect(fn, deps) runs fn after React shows a render. If fn returns a function, that is the cleanup: React calls it before the effect runs again, and when the component is removed. The deps decide when the effect runs again: [] never, no deps after every render, [x] when x changes.

React compares deps with Object.is. Numbers and strings are compared by value, objects and arrays by identity. An object written in the component's body is born again every render, so an effect that depends on it runs every render.

<StrictMode> works in development: for every newly mounted component React runs the effect, the cleanup, then the effect again. An effect with a tidy cleanup is not bothered; one that forgets its cleanup is caught, because what it leaves behind doubles. In a production build StrictMode is inert, so this world asks React for the same check through <Activity>: hidden, then shown again.

An effect's function is a closure: it keeps the values of the render it was made in. If the effect never runs again (deps []), an interval inside it keeps reading old values. The ways out: put that value in the deps, use the updater setCount(c => c + 1), or read it from a ref.

useLayoutEffect runs after React changes the DOM but before the browser paints the screen: the place to measure and correct the layout without a flicker. useEffect runs after the screen is painted. Within one commit, every layout effect finishes first, then the regular ones.

Effects are for keeping a component in step with the world outside: the network, timers, the DOM, subscriptions. A value that can be worked out from props or state is simply worked out during render. Keeping it through an effect makes an extra render, and the screen shows the old number for a moment.