React — Interview Questions & Mental Models
Class lifecycle vs hooks (the mapping)
- Interviewers ask 'lifecycle' even in function components — they mean when effects run and when state updates.
- constructor → initial state / one-time setup; prefer useState initialiser or lazy init useState(() => ...).
- render → the function body runs every time React needs to render.
- componentDidMount → useEffect(() => { ... }, []) — after paint, browser has committed DOM.
- componentDidUpdate → useEffect(() => { ... }, [deps]) — runs after render when deps changed.
- componentWillUnmount (cleanup) → return a function from useEffect: useEffect(() => { return () => cleanup(); }, [deps]).
- getDerivedStateFromProps → prefer controlled props or key to reset state.
- Follow-up: useLayoutEffect fires synchronously after DOM mutations before paint; useEffect fires after paint. Use layout effect for measuring DOM or avoiding flicker.