Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why componentWillMount should not be used?

Firing server call to fetch data in componentWillMount life cycle method a bad practice?

And why it is better to use componentDidMount.

like image 358
Lokesh Agrawal Avatar asked Sep 04 '17 20:09

Lokesh Agrawal


People also ask

Why is componentWillMount deprecated?

The reason for this decision is twofold: All three methods are frequently use incorrectly and there are better alternatives. When asynchronous rendering is implemented in React, misuse of these will be problematic, and the interrupting behavior of error handling could result in memory leaks.

Can I use componentWillMount?

You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a hook based component.

Is it good to use setState () in componentWillMount () method?

Yes, it is safe to use setState() inside componentWillMount() method.


2 Answers

UPDATE: componentWillMount will soon be deprecated.


To cite @Dan Abramov

In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.

Read more here.

like image 96
Lyubomir Avatar answered Sep 24 '22 20:09

Lyubomir


UPDATE - may / 2018
There is a new feature for react in a working progress called async rendering.
As of react v16.3.2 these methods are not "safe" to use:

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

you can read more about it in the docs.


As a general rule don't use componentWillMount at all (if you use the es6 class syntax). use the constructor method instead.
This life-cycle method is good for a sync state initialization.
componentDidMount in the other hand is good for async state manipulation.

Why?
Well, when you do an async request in the constructor / componentWillMount you do it before render gets called, by the time the async operation has finished the render method most probably already finished and no point to set the "initial state" at this stage is it?.
I'm not sure this is your case here, but most of the cases that developers wants to initiate state asynchronously in componentWillMount is to avoid a second render call. but you can't avoid it can you, like mentioned above, render will fire anyway before the async operation will finish.
So, the best time to call an async operation is after a render has called and the component mounted (you could mount null or an empty <div/>) and then fetch your data, set the state and make it re-render respectively.

like image 37
Sagiv b.g Avatar answered Sep 23 '22 20:09

Sagiv b.g