What do the Rules of Hooks protect, and when is useEffect the wrong tool?
Hooks must run in the same order. Effects are for syncing with the outside world.
Points worth saying
- Hooks are called unconditionally so React can match state to call order.
- useEffect runs after paint and is for subscriptions, timers, and DOM that React does not own.
- Derived state and event handlers often do not need an effect.
A full answer
React associates hook state with the order of calls in a component. If you call a hook inside a condition, that order changes between renders and React loses track of which state belongs where.
useEffect is for synchronizing with something outside React: a WebSocket, a document title, or a third-party widget. If you can compute a value during render from props and state, do that instead of storing it in an effect.
In an interview, name the cleanup. An effect that subscribes must return an unsubscribe. An effect that fetches should ignore stale responses or abort the request. That shows you think about lifetime, not only the happy path.
Mark your progress
Create a practice profile to mark this question.