React LifeCycle Methods for V-0.16 x
Last updated
Last updated
Lifecycle methods are various methods which are invoked at different phases of the lifecycle of a component.
Deprecation of methods and introduction of static lifecycle methods
In React 16.3 few lifecycle methods have been deprecated. For now, these methods are prefixed with UNSAFE_
and will be fully removed in the next major release. Meanwhile, the existing react apps can be gradually migrated to new React lifecycle methods.
Methods like componentWillMount
, componentWillReceiveProps
and componentWillUpdate
were heavily misused because the current instance thiswas available and is easy to misuse. The react team decided and removed the error-prone methods to make the whole react component lifecycle much simpler.
Seeking to improve the UX and performance of React, the team is moving towards async rendering. The motivation behind the static lifecycle method is mostly to make the methods easier and compatible with async rendering.
Watch this amazing demo by Dan Abramov on async rendering.
The methods that are deprecated are as follows:
componentWillMount
All the legacy use cases are covered in the constructor. This is renamed as UNSAFE_componentWillMount
.
componentWillReceiveProps
The new static method getDerivedStateFromProps
is safe rewrite for this method and covers all the use cases of componentWillReceiveProps
. The new name for this method is UNSAFE_componentWillReceiveProps
.
componentWillUpdate
The new method getSnapshotBeforeUpdate
is safe rewrite for this method and covers all the use cases of componentWillUpdate
.
The new name for this method is UNSAFE_componentWillUpdate
.
The Phases of latest React component lifecycle
The React component which extends React.Component
goes through the following phases:
Mounting
Updating
Unmounting
The following chart represents the phases and methods of React’s lifecycle.
Let’s understand these phases and how they work, by creating a neat music player to understand the use cases of all the component lifecycle methods.
1) Mounting
In React realm mounting refers to the loading of components on the DOM. This phase contains a set of methods which get invoked when the component is getting initialized, and loaded on to the DOM.
The methods which get called are as follows:
constructor This is the first method that gets called whenever a component is created. The constructor is called only once in the whole lifecycle of a component. It’s used to set up the initial values of variables and component state. Usage: Setup the initial state of the component.
If we render the above component as <ContraMusicPlayer/>
it will by default render with volume level at 70 and it will be in the paused state.
In React’s realm the constructor is the only place where this.state
should be used. Every other method should update the state using this.setState()
.
static getDerivedStateFromProps
As the name suggests getting the derived state from props is used when the state is dependent on props, hence whenever the props are changed the state has to be kept in sync.
This method is invoked after the constructor and is expected to return an object to update the state of the component. If null is returned then, nothing is changed in the state.
The method getDerivedStateFromProps
is static, hence it has no access to this
. This method has access to the current state and props. Hence, if the state is dependent on props then the state can be updated here. This method is the brand new addition in React v16.3+. Usage: Keep the state synced with incoming props. This method is a safer replacement of componentWillReceiveProps
. This method is a pure function, hence nothing should be written which creates side effects.
In the above example, to keep track of changes in props value, the specific value is mirrored in the state to compare with upcoming new props.
There are a few ways to avoid using derived state from props (learn more).
render This is the required method in a React component, as this method prepares the element that gets mounted on to the browser DOM. This method is pure, which means it gives the same output every time the same input is provided. This method should not result in any side effect like changing state.
componentDidMount This is the hook method which is invoked immediately after the component did mount on the browser DOM. Usage: All the interaction directly with the browser DOM and integrate with third-party libraries like Highcharts or D3 should be done here. E.g This method is best to draw sound wave graphs of songs.
The following example shows the setup of Highcharts when the DOM is ready
Where should you make the API calls?
The API calls should be made in componentDidMount method always.
Please refer the following blog post to learn more.Where to integrate API calls in ReactJs? — componentWillMount vs componentDidMount Every React application which wants to fetch data or send data to the server needs to integrate APIs.hackernoon.com
2) Updating
This phase starts when the react component has taken birth on the browser and grows by receiving new updates. The component can be updated in two ways, sending new props from parents or updating the current state.
The list of methods that will get called in sequence when the update happens in either way:
static getDerivedStateFromProps This method behaves exactly as defined above in mounting phase.
shouldComponentUpdate This method tells React that when the component is being updated, it should re-render or skip rendering altogether. This method is a question, should the Component be Updated? Hence this method should return true or false, and accordingly, the component would be re-rendered or skipped. By default, this method returns true. Usage: The example is one of the cases where the render is quite costly and we would like to re-render the component only when the props status changes. For example, let’s say that for every render, the component generates a thousand prime numbers. If some apps has this kind of logic, then we can control when it is required and make sure the component is rendered.
render And then the component gets rendered (details in mounting phase).
getSnapshotBeforeUpdate
This method gets called after the render created the React element and before it is actually updated from virtual DOM to actual DOM. This phase is known as pre-commit
phase.
This method has access to both previous and current props and state.
If the method getSnapshotBeforeUpdate
returns a value, the same is available in componentDidUpdate
as the third parameter, where the UI can be updated to make is synced before and after render.
Usage: This method is useful if you want to keep sync in-between state of current DOM with the updated DOM. E.g. scroll position, audio/video, text-selection, cursor position, tool-tip position, etc.
To learn more from Dan Abramov please follow the link.
componentDidUpdate is executed when the newly updated component has been updated in the DOM. This method is used to re-trigger the third party libraries used, and to make sure these libraries also update and reload themselves.
Usage: The use cases are mostly similar to the use case of componentDidMount
to keep the third party library or UI in sync with every update.
3) Unmounting
In this phase, the component is not needed and the component will get unmounted from the DOM. Below is the method called in this phase:
componentWillUnmount This method is the last method in the lifecycle. This is executed just before the component gets removed from the DOM. Usage: In this method, we do all the cleanups related to the component. For example, on log out, the user details and all the auth tokens can be cleared before unmounting the main component.
Wrapping-up