29

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

And why it is better to use componentDidMount.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
ThinkGeek
  • 4,749
  • 13
  • 44
  • 91

5 Answers5

24

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.

Lyubomir
  • 19,615
  • 6
  • 55
  • 69
  • 3
    This is what I read sometime back but never had a justifiable reason on why it will get called multiple times. – ThinkGeek Sep 05 '17 at 03:54
  • This is a link only answer that does not explain the "why" context of the question. Any of the other responses answer the question better, so this should not be the accepted answer. – JGallardo Sep 26 '19 at 01:12
  • Sorry if my question is stupid. If I fetch data in componentWillMount, even if it does not break the component that is rendered for the first time, whether the fetch data function in` componentWillMount` will be called a bit earlier than the fetch data componentDidMount function, resulting in Do we get the data a little faster? – Duy Hưng Androgyne Tenor May 07 '20 at 03:34
23

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.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • 1
    Correct, explanation with async calls example gives enough reason for not using componentwillmount. Thanks buddy :) – ThinkGeek Sep 05 '17 at 03:53
  • Sorry if my question is stupid. If I fetch data in componentWillMount, even if it does not break the component that is rendered for the first time, whether the fetch data function in` componentWillMount` will be called a bit earlier than the fetch data componentDidMount function, resulting in Do we get the data a little faster? – Duy Hưng Androgyne Tenor May 07 '20 at 03:39
  • 1
    @DuyHưngAndrogyneTenor No, because it doesn't matter when you get the data, what matters is when can you do something with it. The fact that the data is being handled in an async operation, it will only run after ALL sync work is done. So i doubt there's a difference. – Sagiv b.g May 07 '20 at 08:32
  • @Sagivb.g: Yea, thank so much, so, all process from constructor, mounting to end of rendering are synchronus actions, right? And those will go to callstack before async actions? – Duy Hưng Androgyne Tenor May 15 '20 at 14:15
  • @DuyHưngAndrogyneTenor All user's code (not react's code like `setState` for example) is sync. So yeah, our code will run to completion before async code. Unless of course when we use async API's like setTimeout promise etc.. – Sagiv b.g May 15 '20 at 14:19
9

componentDidMount is the best place to put calls to fetch data, for two reasons:

  1. Using componentDidMount makes it clear that data won’t be loaded until after the initial render. You need to setup initial state properly, so you don’t get undefined state that causes errors.

  2. If you need to render your app on the server, componentWillMount will be called twice(on the server and again on the client), which is probably not what you want. Putting the data loading code in componentDidMount will ensure that data is only fetched from the client. Generally, you should not add side effects to componentWillMount.

mradziwon
  • 1,206
  • 1
  • 9
  • 13
3

Component Mounting life cycle is

  • constructor()
  • componentWillMount() /UNSAFE_componentWillMount()(react 16)
  • render()
  • componentDidMount()

Constructor and componentWillMount both call before render() call which is responsible for page rendering.

Here State initialized is done in Constructor and api are called in componentDidMount because of async calls.

ComponentWillMount was good to initialized state before ES6 when constructor was not there. But now ComponentWillMount is good for nothing and react team is thinking it after react 17.

In addition to above, react have moved to react fiber architecture, to avoid unnecessary re-rendering and improve performance, react has decided to move away from componentWillMount, componentWillReciveProps and componentWillUpdate methods.

  • 2
    it's not answering why componentWillMount is unsafe and is not used for data fetching. – Evgeny Timoshenko May 17 '18 at 08:18
  • This is the official statement of React. They introduced it for good reason and now because of ES6 it is no longer needed so React team itself declare it as unsafe. and recommends use of constructor() over componentWillMount(). – Devinder Suthwal May 17 '18 at 12:50
2

The way I understand it, one of the biggest reasons has to do with setting up the right expectations for the developers reading the code.

If we use componentWillMount it's tempting to think that the fetch have time to happen, then the component "did" mount, and then the first render will happen. But that it not the case. If we do an async call (like an API call with Promises), the component will actually run render before the fetch can return and set the component state (or change the Redux state, or what ever).

If we instead use componentDidMount, then it's clear that the component will render at least once before you get back any data (because the component already did mount). So, by extension, it's also clear that we have to handle the initial state in a way so that the component doesn't break on the first ("empty") render.

jonahe
  • 4,820
  • 1
  • 15
  • 19