Component Lifecycle 🔁
Even though modern React relies on hooks, understanding class lifecycles helps when reading legacy code or migrating components.
1) Mounting Phase 🌱
| Class Method | Purpose | Hook Equivalent |
|---|---|---|
constructor | Initialize state, bind methods | useState, inline arrow handlers |
componentWillMount (legacy) | Deprecated; avoid side effects here | N/A |
render | Returns JSX | Function body return |
componentDidMount | Runs once after first paint | useEffect(() => { ... }, []) |
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 Method | When It Runs | Hook Pattern |
|---|---|---|
shouldComponentUpdate | Let React skip re-render | React.memo, useMemo, useCallback |
componentDidUpdate | After props or state change | useEffect without empty array, compare deps |
getDerivedStateFromProps | Compute derived state | Prefer 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 Method | Hook Equivalent |
|---|---|
componentWillUnmount | Return cleanup function inside useEffect |
useEffect(() => {
const subscription = socket.connect();
return () => subscription.disconnect();
}, []);4) Error Handling 🛡️
| Class Method | Description | Hook Alternative |
|---|---|---|
componentDidCatch & getDerivedStateFromError | Error boundaries | Still class-based today; wrap hook components with class boundaries |
5) Migration Checklist ✅
- Convert
statetouseStateoruseReducer. - Move side effects from
componentDidMount/UpdateintouseEffectand list dependencies. - Replace lifecycle condition checks with early returns or memoization.
- Use
useReffor 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