Skip to Content
FrontendReactBasics1.6 React Component Lifecycle

Component Lifecycle 🔁

Even though modern React relies on hooks, understanding class lifecycles helps when reading legacy code or migrating components.

1) Mounting Phase 🌱

Class MethodPurposeHook Equivalent
constructorInitialize state, bind methodsuseState, inline arrow handlers
componentWillMount (legacy)Deprecated; avoid side effects hereN/A
renderReturns JSXFunction body return
componentDidMountRuns once after first paintuseEffect(() => { ... }, [])

Example

class LegacyTimer extends React.Component { state = { tick: 0 }; componentDidMount() { this.interval = setInterval(() => this.setState({ tick: this.state.tick + 1 }), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return <p>Tick: {this.state.tick}</p>; } }
function Timer() { const [tick, setTick] = useState(0); useEffect(() => { const id = setInterval(() => setTick(t => t + 1), 1000); return () => clearInterval(id); }, []); return <p>Tick: {tick}</p>; }

2) Updating Phase ♻️

Class MethodWhen It RunsHook Pattern
shouldComponentUpdateLet React skip re-renderReact.memo, useMemo, useCallback
componentDidUpdateAfter props or state changeuseEffect without empty array, compare deps
getDerivedStateFromPropsCompute derived statePrefer derived calculations in render or useMemo; use reducer if needed

Hooks Tip 🧠

useEffect(() => { // runs after count changes document.title = `Count: ${count}`; }, [count]);

3) Unmounting Phase 🧹

Class MethodHook Equivalent
componentWillUnmountReturn cleanup function inside useEffect
useEffect(() => { const subscription = socket.connect(); return () => subscription.disconnect(); }, []);

4) Error Handling 🛡️

Class MethodDescriptionHook Alternative
componentDidCatch & getDerivedStateFromErrorError boundariesStill class-based today; wrap hook components with class boundaries

5) Migration Checklist ✅

  1. Convert state to useState or useReducer.
  2. Move side effects from componentDidMount/Update into useEffect and list dependencies.
  3. Replace lifecycle condition checks with early returns or memoization.
  4. Use useRef for instance fields (this.someRef).

🧱 Remember: function components render on every update, so keep effects pure and handle cleanup explicitly.

Recap 🔄

Class lifecycles map cleanly to hooks: mount/update/unmount logic fits into useEffect, memoization replaces shouldComponentUpdate, and refs hold mutable instance data. Understanding both models keeps migrations predictable and legacy code approachable.

Last updated on