Lifecycle Methods in Class Components
In a Class Component, the lifecycle is split into 3 main phases:
Lifecycle Methods in Class Components
Lifecycle Methods
In a Class Component, the lifecycle is split into 3 main phases:
- Mounting: the component is created and inserted into the DOM for the first time.
- Updating: the component re-renders when its
propsorstatechange. - Unmounting: the component is removed from the DOM.
1. The Mounting Phase
These methods are called in order when a component is created and inserted into the DOM:
constructor()
- When does it run? Runs first, even before the component is attached to the DOM.
- Purpose:
- Initialize the component's
state. - Bind methods (event handlers).
- Initialize the component's
- Note: This is the only place you can assign
this.statedirectly. In every other method, you must usethis.setState().
constructor(props) {
super(props); // Must always call super(props) first
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this);
}
static getDerivedStateFromProps()
- When does it run? Runs right before
render(), both on the initial mount and on subsequent updates. - Purpose: Lets a component update its
statebased on changes toprops. This is a rarely used method and should only be used in special cases. - Note: It returns an object to update
state, ornullif nothing needs to change.
render()
- When does it run? Runs after
constructor()(andgetDerivedStateFromProps()if present). - Purpose: This is the only required method. It reads
this.propsandthis.stateand returns React elements (usually JSX) describing the UI. - Note:
render()must be a "pure" function - it must not modifystateor interact with anything external (like calling an API).
componentDidMount()
- When does it run? Runs immediately after the component has been rendered and attached to the DOM tree.
- Purpose: This is the ideal place to perform tasks that require the DOM to be ready, or that need to interact with the outside world.
- Call an API to fetch data from the server.
- Set up subscriptions (like
setInterval,addEventListener). - Interact directly with the DOM if needed.
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data: data }));
}
2. The Updating Phase
A component updates whenever its props or state change. The following methods are called in order:
-
static getDerivedStateFromProps(): (as explained above). -
shouldComponentUpdate(nextProps, nextState)- When does it run? Runs before
render()whenever there are newpropsorstate. - Purpose: Lets you control whether the component should re-render at all. By default it always returns
true. - Note: You can optimize performance by comparing
nextPropswiththis.propsandnextStatewiththis.state. Returningfalsestops the update process (skippingrender()andcomponentDidUpdate()).
- When does it run? Runs before
-
render(): (as explained above). -
getSnapshotBeforeUpdate(prevProps, prevState)- When does it run? Runs right after
render()but before the render output is committed to the DOM. - Purpose: Lets you "capture" some information from the DOM (e.g., scroll position) before it might change. The return value of this method is passed into
componentDidUpdate().
- When does it run? Runs right after
-
componentDidUpdate(prevProps, prevState, snapshot)- When does it run? Runs immediately after the component has been updated and re-rendered in the DOM.
- Purpose: Similar to
componentDidMount(), this is where you perform tasks after the UI has been updated.- Call an API if
propshave changed (must add a condition to avoid infinite loops). - Interact with the DOM based on the update result.
- Call an API if
componentDidUpdate(prevProps) {
// Only call the API if the 'userId' prop changed
if (this.props.userId !== prevProps.userId) {
this.fetchUserData(this.props.userId);
}
}
3. The Unmounting Phase
This method is called when a component is about to be removed from the DOM.
componentWillUnmount()
- When does it run? Runs right before the component is removed and destroyed.
- Purpose: This is where you "clean up" everything that was set up in
componentDidMount(). * Cancel subscriptions (e.g.,clearInterval,removeEventListener). * Cancel any in-flight network requests (API calls).
componentWillUnmount() {
clearInterval(this.myInterval);
window.removeEventListener('resize', this.handleResize);
}
Comparison with Functional Components (Hooks)
With the introduction of Hooks, these Class Component lifecycle methods can be mapped onto useEffect in Functional Components:
componentDidMount()→useEffect(() => { ... }, [])componentDidUpdate()→useEffect(() => { ... }, [dependency1, dependency2])componentWillUnmount()→useEffect(() => { return () => { ... } }, [])
