I am working with React and I am trying to understand the lifecycle. I am doing a componentWillMount
method in order to get the props
I need before
It's not weird at all. componentWillMount
will fire before render, and in the first-pass you are invoking an action to get the dealers GetDealersActions.getDealers();
which is basically an async command. Since it is async, the component will render once before it gets data, and then again after the store publishes a changed
event, which will re-trigger rendering.
Here is an approximation of the sequence of actions happening in your example:
componentWillMount
invokes getDealers
command (which is async)render
with default component statedealer
datachanged
event, which re-triggers renderingrender
invoked with the dealer
data in component state.The problem is that React will run it's lifecycle methods in a certain sequence, not caring about you invoking some async method. So basically you don't have a way to stop rendering
just because you invoked a command to get the dealers
. That is a limitation of react
(or a feature), which surfaces when combined with async programming and you should accept it as is.
If you accept the fact that React will render twice, you can utilize that in your favor, so on first render you could just show a loading
indicator (e.g. a spinning wheel) and when the data loads you just display it in the second render
.
However, if you are not convinced and still want to avoid double-rendering in the initial load, you could do prefetching of the data before you mount the application component, which would ensure that initial data is loaded in the store before the first render
, which would mean that you wouldn't have to invoke getDealers
in componentWillMount
since the data would already be in the store on the first render
.
As a reminder, double-rendering is not a significant performance problem, like it would be in Angular.js or Ember.js, since React is very efficient at DOM manipulation, but it could produce some UX issues if not handled properly.