From methods to effects
Older class components had named lifecycle methods for mounting, updating, and unmounting. Function components replace those with the effect hook, which runs after the browser paints. One mental model covers all phases through a single api.
- Mount is the first render when the effect runs once.
- Update is any rerender that may run the effect again.
- Unmount is removal when the cleanup function runs.
Reading an effect
An effect takes a setup function and an optional dependency array. The setup runs after render, and any function it returns is the cleanup. The browser calls cleanup before the next effect run and again when the component leaves the tree.
- An empty array runs setup once on mount.
- A populated array reruns when those values change.
- The returned function tears down subscriptions or timers.
Thinking in terms of synchronizing with external systems, rather than discrete lifecycle events, leads to clearer effect code.
Key idea
The effect hook unifies mount, update, and unmount by running setup after render and a returned cleanup before the next run or on removal.