Explain the React component lifecycle techniques in detail
React components are the reusable and independent bits of code that help build the user interface of a webpage. Each of these components has various lifecycle methods which are invoked at different stages of their lifecycle. They are mainly required to free up the resources taken up by the multiple components which help the webpage render seamlessly and provide the users with a great experience. There are 4 stages in the lifecycle of a react component.
Prerequisite: To understand these concepts, you have to understand the basics of React.
1. Initialization: It is the first stage of a React components’ lifecycle. In this stage, the component is defined with the default props and its initial state in the constructor of the component. This phase occurs only once in the lifecycle before the creation of the component or any props from the parent is passed into it and consists of the following methods which are called in the same order.
- constructor(): This method is called before the component is mounted. This is only used for two purposes: Initializing local state by assigning an object to “this.state” and binding the event handler methods to an instance. The following code snippet is a good example of its usage.
Note: The following methods only work with the “create-react-class” module and would throw errors with ES6 classes.
- getDefaultProps(): This method can be used to define the default value of “this.props“. Also, we need to initialize the createReactClass before writing anything else for using these methods. We can see an example of its usage below.
- getInitialState(): This method can be used to define the default value of “this.state“. The code snippet below would display a greeting message “Hello!” when we click the button on the output webpage.
2. Mounting: It is the second stage of a React components’ lifecycle. In this stage, the component is mounted on the DOM and rendered for the first time on the webpage after the component has been initialized. It consists of the following methods which are called in the same order.
- getDerivedStateFromProps(): This method is invoked on the initial mount and any subsequent updates right before calling the render() method. To update the state, it returns an object and to update nothing, it returns null.
- render(): This method is responsible for returning a single root HTML node element defined in each component. When called, this method examines “this.props” and “this.state” and returns one of the following types:
- React elements
- Arrays and fragments
- String and numbers
- Booleans or null
- componentDidMount(): This method is invoked immediately after the render() method. Now, we can perform any querying operations with the DOM.
Note: The method below is considered legacy and should be avoided in new code.
- componentWillMount(): This method is invoked right before the render() method. The component will not re-render if setState() is called inside this method.
3. Updating: It is the third stage of a React components’ lifecycle. In this stage, the state and props are updated following various user events like clicking on a button, pressing a certain key, etc. We can communicate with the hierarchy of the components and handle user interaction on the webpage. It allows us to ensure that the component is presenting its latest version as required, therefore, it is called multiple times. It consists of the following methods.
- shouldComponentUpdate(): This method is invoked before the render() method when new props or states are being received and the DOM is decided to be updated by the component. It can be used as performance optimization and helps control the behavior of the component’s updates. The component will update if this method returns true or skip the updating if it returns false.
- render(): This method is invoked again to examine “this.props” and “this.state”. The code inside the render() method will be invoked again if shouldComponentUpdate() returns false so that the component is displayed properly.
- getSnapshotBeforeUpdate(): This method is invoked just before the DOM is updated with the latest rendered output. It helps to capture information before it is potentially changed (like scroll position) from the DOM. It returns a snapshot value or null.
- componentDidUpdate(): This method is invoked immediately after the component is updated. We can use this method to execute a block of code once after the rendering. It is not called for the initial rendering.
Note: The methods below are considered legacy and should be avoided in new code.
- componentWillUpdate() – This method is invoked when new props or states are being received just before rendering of the component. It can be used to prepare before an update occurs. If shouldComponentUpdate() returns false, it will not be called. This method is not called for the initial render.
- componentWillRecieveProps() – This method is invoked before new props are received by a mounted component. To perform state transition by using the “this.setState()” method, we should compare “this.props” and nextProps if we want to update the state in response to prop changes. React only calls this method if some of the components’ props are updated. It doesn’t call this method with initial props during the mounting stage.
4. Unmounting: It is the fourth and final stage of the React components’ lifecycle. It is invoked when the components’ instance is unmounted and destroyed from the DOM. This stage only contains a single method.
- componentWillUnmount(): This method is invoked immediately before a component is permanently unmounted and destroyed. It does the necessary cleanup tasks like event listeners, cleaning up DOM elements, invalidating timers or canceling network requests. We cannot mount a component again after its instance is unmounted.
Example: Let’s take a look at the code snippet below which displays a demonstration of most of the lifecycle methods we have read about so far.
Firstly, create a react app and open the index.js file from the src folder.
Step to run the application: Open the terminal and type the following command.