Effects

Rendering must be pure: a component reads props and state and returns JSX, and nothing else. Real applications still have to talk to the world outside React 7,897 — a WebSocket, a <video> element, localStorage, an analytics script, an HTTP API. An effect is the escape hatch for that work. It is a function React runs after it has committed your JSX to the DOM, so by the time it runs the nodes it touches already exist.

The mental model that causes the most bugs is the one inherited from class components, where componentDidMount and componentDidUpdate were things that happened at a point in time. An effect is not an event. It describes how to keep an external system synchronized with the current props and state, plus how to undo that synchronization — and React decides when to run each half.

Where useEffect and useLayoutEffect run in one update
Where useEffect and useLayoutEffect run in one update

Everything here follows from that picture: the dependency array decides when React re-synchronizes, the cleanup decides how it un-synchronizes, and the two ways that pair fails are running too often and running with stale values.

Subsections