React components go through 3 main phases during their lifetime:
🧭 1. Mounting Phase (Component is being created and inserted into the DOM)
Method
Purpose
constructor()
Initialize state and bind methods
static getDerivedStateFromProps()
Update state based on props (rarely used)
render()
Return JSX to display UI
componentDidMount()
Run side effects (API call, subscriptions) after mount
🔁 2. Updating Phase (Component is re-rendered due to props/state changes)
Method
Purpose
static getDerivedStateFromProps()
Called on every update too
shouldComponentUpdate()
Decide whether to re-render (return true/false)
render()
Re-render JSX
getSnapshotBeforeUpdate()
Capture DOM state before update (e.g., scroll position)
componentDidUpdate()
Perform side effects after update (e.g., fetch on prop change)
❌ 3. Unmounting Phase (Component is removed from the DOM)
Method
Purpose
componentWillUnmount()
Cleanup tasks (e.g., clearInterval, unsubscribe)
🧪 Example: Lifecycle in Class Component
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
console.log("Constructor");
}
componentDidMount() {
console.log("Component Mounted");
}
shouldComponentUpdate(nextProps, nextState) {
return true; // Default is true
}
componentDidUpdate(prevProps, prevState) {
console.log("Component Updated");
}
componentWillUnmount() {
console.log("Component Will Unmount");
}
render() {
return <h1>{this.state.count}</h1>;
}
}
✅ Lifecycle in Functional Components (using Hooks)
Class Method
Equivalent in Hooks
componentDidMount
useEffect(() => {}, [])
componentDidUpdate
useEffect(() => {...}, [deps])
componentWillUnmount
useEffect(() => { return () => {...} }, [])
🎯 Summary
Class components have detailed lifecycle methods.
Functional components use useEffect() to handle lifecycle behavior.
Hooks are the modern standard in React for managing lifecycle events.