React — Interview Questions & Mental Models
useEffect — what interviewers want to hear
- Purpose: synchronise component with external systems (network, subscriptions, timers, browser APIs), not to derive values you can compute during render.
- Dependency array: exhaustive deps = effect re-runs when those values change. Stale closures happen when you omit deps without eslint-plugin-react-hooks.
- Cleanup: runs before re-run of the effect (on dep change) and on unmount — ideal for abort controllers, unsubscribing, clearing intervals.
- Strict Mode (dev): React may mount → unmount → mount once to surface missing cleanup. Double useEffect in dev is intentional.
- Classic Q: empty deps [] — when is it wrong? When the effect should react to props/state changes but you froze it — leads to bugs.
1useEffect(() => {
2 const ac = new AbortController()
3 fetch(url, { signal: ac.signal }).then(/* ... */)
4 return () => ac.abort()
5}, [url])