user911625
user911625

Reputation:

In React how to decide whether to use componentWillReceiveProps or componentWillMount?

componentWillMount is called once at first render

componentWillReceiveProps is called for subsequent renders

So - if I want to do some action (e.g. initialise some data in a store) when the component is rendered where do I put this code? - Which depends on a prop passed in from a higher level component.

The problem is I don't know for sure if the prop will be initialised by the time the first render is called. (The prop depends on asynchronous data). So - I can't put the code in componentWillMount. But if I put it in componentWillReceiveProps and then change something higher up the component chain so that the data is fulfilled synchronously now my code in componentWillReceiveProps is never run. The motivation for this post is that I just did just that and now have to refactor a bunch of components.

It seems the only solution is to put the code in both methods.

There is no lifecycle method which is always called - for the first time and subsequent. But how can you know for sure if your data in top level components will necessarily be available by the time of the first render? Or for that matter necessarily not. Or maybe you can be - but then you change this.

This lifecyle approach seems very fragile to me. Have I missed something? (Most likely).

Upvotes: 6

Views: 3913

Answers (1)

Tom Chen
Tom Chen

Reputation: 1519

You already have the answer: put the code in both methods. However, I'd suggest to convert the props to state in both methods, and use the state as your single source of truth.

componentWillMount () {
  this.checkAndUpdateState(this.props);
}

componentWillReceiveProps (nextProps) {
  this.checkAndUpdateState(nextProps);
}

checkAndUpdateState (props) {
  this.setState({ isLoaded: !!props.yourData });
}

Upvotes: 8

Related Questions