React Lab · LAB-04Under investigation
“useEffect is for everything.”
An effect synchronises your component with an external system. If there is no external system, you probably do not need one.
- Verdict
- BUSTED
- Level
- DEVELOPER
- Division
- LAB-04
- References
- 02
Investigation
Things that are not effects
- 01Deriving a value from props or state, compute it during render.
- 02Resetting state when a prop changes, change the key instead.
- 03Responding to a user event, put the logic in the event handler.
- 04Fetching data on mount, use the framework's data layer or a query library, which handles races, caching and cancellation.
- 05Transforming data for display, a plain function, memoised only if measurably expensive.
The failure mode is an extra render plus a window where the two values disagree. An effect runs *after* paint, so the user can see the inconsistent frame.
example.jsxjsx
// Renders twice, and the first frame shows the old totaluseEffect(() => setTotal(items.reduce(sum, 0)), [items]);// Renders once, always consistentconst total = items.reduce(sum, 0);References
- 01React docsYou might not need an effect
- 02React docsSynchronizing with effects