Question presented to candidate: "Walk me through a component's lifecycle in a function component. What runs, and in what order?"
What a strong answer should cover:
- Three phases: mount, update, unmount — the class method names map onto hooks, they were not replaced by something conceptually different.
- Mount: render → layout effects → browser paints → passive effects.
useLayoutEffectruns before paint,useEffectafter. - Update: render → the previous layout effect's cleanup → the new layout effect → the previous passive cleanup → the new passive effect. Cleanup of the old always precedes setup of the new, per hook.
- Unmount: cleanups only, layout before passive.
- An effect's cleanup is not just "on unmount" — it runs before every re-run, which is what makes subscriptions and timers safe.
useEffectwith[]is not exactlycomponentDidMount: in StrictMode development React mounts, unmounts and remounts, so it runs twice. That is a test of your cleanup, not a bug.- There is no lifecycle hook for "props changed" — you express that as a dependency array, or derive the value during render.
- The render phase must be pure; anything with a side effect belongs in an effect.
Clarifying questions expected:
- "Function components or class components?" — the class names still come up in interviews.
- "Do you need this before the browser paints?" — that is the
useLayoutEffectquestion.
Code / implementation expected: Optional. A component that logs each phase makes the ordering concrete.