Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between componentWillMount and UNSAFE_componentWillMount in ReactJS

Tags:

reactjs

this is react doc. This lifecycle was previously named componentWillMount. That name will continue to work until version 17. But What's the difference between componentWillMount and UNSAFE_componentWillMount in ReactJS.

like image 651
ltoddy Avatar asked Aug 10 '18 12:08

ltoddy


People also ask

What is difference between componentWillMount and componentDidMount?

componentDidMount() is only called once, on the client, compared to componentWillMount() which is called twice, once to the server and once on the client. It is called after the initial render when the client received data from the server and before the data is displayed in the browser.

What is the use of componentWillMount in react JS?

The componentWillMount() lifecycle hook is primarily used to implement server-side logic before the actual rendering happens, such as making an API call to the server. In this guide, you will learn to use componentWillMount() and make API calls after the initial component rendering.

What is componentWillMount replaced by?

The function is replaced with class constructor.

What is UNSAFE_componentWillMount?

UNSAFE_componentWillMount() is invoked just before mounting occurs. It is called before render() , therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead for initializing state.


2 Answers

Both lifecycle methods do the same in React 16.

The difference is that componentWillMount will not exist in future versions of React from version 17 onward.

So if you want your code to work in future versions of React, you have two choices:

  1. Recommended: use the constructor of the component class instead
  2. Use UNSAFE_componentWillMount

The lifecycle method was renamed to make sure developers realize that there is a better way than using the UNSAFE method.

like image 113
Patrick Hund Avatar answered Oct 22 '22 19:10

Patrick Hund


There is no difference other than the name. This method is now legacy and will be deprecated in the future. Actually this name is an alias for the real one. Like, just a warning that using this method is unsafe.

Using both those names work with the current release. In a future release (16.x) there will be a warning in dev mode. In the 17 release without using UNSAFE prefix this method won't work.

like image 29
devserkan Avatar answered Oct 22 '22 17:10

devserkan