harddebuggingjavascript~14 min
Fix the Effect Runner
Objective: Model the effect lifecycle: compare deps, clean up, then re-run.
This model of `useEffect` re-runs the effect on every call and never runs cleanups. Make it run the previous cleanup before re-running, and skip the effect when the dependencies have not changed.
- `runner.update(effect, deps)` runs the effect only on the first call or when any dep changed (Object.is).
- Before re-running, call the previous cleanup if the effect returned one.
- `runner.unmount()` calls the latest cleanup once.
- An effect that returns a non-function is fine.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- Why does an effect with no dependency array run after every render?
- What is the stale-closure problem when deps are omitted?
- Why does Strict Mode run effects twice in development?