1

I can see that componentWillMount() can be unneeded, but how is it "unsafe"?

Jeremy L
  • 3,770
  • 6
  • 41
  • 62
  • Does this answer your question? [Why componentWillMount should not be used?](https://stackoverflow.com/questions/46043832/why-componentwillmount-should-not-be-used) – Barak Feb 28 '20 at 22:34

1 Answers1

3

I will try to cover the important reasons why these lifecycle cannot be used.

componentWillMount():

Assumption:

People thought that fetching the data inside the componentWillMount will avoid the initial empty rendering of the state, so that the component will not be empty.

What actually happened:

  1. The render of the component happens immediately after the componentWillMount called. Therefore, If there is a delay in the data fetch, the component will still show a loading state.

  2. When making an API call, The browser will continue to process the other stuff in the application while the API call gets the data from the server. So, React will still continue to render the component regardless whether the component has data or not

  3. componentWillMount() will be called twice: once to the server and once on the client.

Solution:

To overcome this misleading understanding, componentDidMount() was introduced which will be called only once when receiving the data.

componentWillUpdate():

Assumption:

People thought that componentWillUpdate calls whenever there is an update in the state (by calling setState), which will update the component.

What actually happened:

Yes, the component was updating each time when there is a state update inside the componentWillUpdate, but when there is an external callback, the componentWillUpdate called multiple times for a single update. (Believe me, I have faced this issue :P).

Solution:

To avoid this issue, componentDidUpdate() is introduced, which will invoked only once per update.

Note:

componentWillReceiveProps is also unsafe for the same reason of componentWillUpdate

For more information, refer this docs

Hope it helps :)

Arun AK
  • 4,353
  • 2
  • 23
  • 46