React is a popular JavaScript library for building user interfaces. One of the key features of React is its life cycle methods. These methods allow you to control what happens when a component is created, updated, or destroyed. In this blog post, we will take a deep dive into the life cycle of React and explore each method in detail.
Before we get started, it’s important to note that the life cycle methods have changed with the introduction of React 16. If you are using an older version of React, some of the methods may be different.
Why Lifecycle is important?
The life cycle of React JS Around us, everything goes through a cycle of taking birth, growing, and at some point in time, it will die. Consider any application, a div container
or UI component in a web browser, each of these takes birth, grows by getting updates, and dies.
The lifecycle methods are various methods that are invoked at different phases of the lifecycle of a component.
Having a great understanding of the component lifecycle would excel in your ability to develop quality ReactJS user interfaces
The Four phases are a Life cycle of React JS below image.
class Test extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECIEVE PROPS!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
}
export default Test;
1. Initialization
In this phase, the React component prepares for the upcoming tough journey, by setting up the initial states and default props, if any. when the component is initiated, and it is the natural place to set up the initial state
and other initial values.
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
2. Mounting
After preparing with basic needs, state, and props, our React Component is ready to mount in the browser DOM. This phase gives hook methods for before and after the mounting of components. The methods which get called in this phase are
- componentWillMount
- render
- componentDidMount
componentWillMount is executed just before the React Component is about to mount on the DOM. Hence, after this method, the component will mount. All the things that you want to do before a component mounts have to be defined here. This method is executed once in a lifecycle of a component and before the first render.
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
render mounts the component onto the browser. This is a pure method, which means it gives the same output every time the same input is provided.
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
componentDidMount this is the hook method that is executed after the component did mount on the dom.
This method is executed once in a component’s lifecycle and after the first render.
componentDidUpdate(prevProps, prevState, snapshot)
3. Update
This phase starts when the react component has taken birth on the browser and grows by receiving new updates. The component can be updated by two ways, sending new props or updating the state.
Let’s see the list of hook methods when the current state is updated by calling the set State
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
- componentWillReceiveProps
shouldComponentUpdate to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases, you should rely on the default behavior.
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate is invoked just before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
componentWillUpdate(nextProps, nextState)
componentDidUpdate is called after and can be useful to perform some action when the state changes. and it takes as its first two arguments the previous props and the previous state.
For example, in the code below we check if the previous state and the current state are different. If they are, the console log statement will be run.
componentDidUpdate(prevProps, prevState) {
if (prevState.pokemons !== this.state.pokemons) {
console.log('pokemons state has changed.')
}
}
componentWillReceiveProps is required if you want to update the state values with new props values, this method will get called whenever any change happens to props values.
componentWillReceiveProps(props){
this.setState({props});
}
4. Unmounting
In this phase, the component is not needed and the component will get unmounted from the DOM. The method which is called in this phase
- componentWillUnmount
componentWillUnmount This method is the last method in the lifecycle. this is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount()
.
componentWillUnmount() {
console.log('component will unmount');
}