React Holiday

Day 17: Always use `Did`, unless you shouldn't

Here is some lifecycle wisdom:

Always use Did methods, unless you shouldn’t.

Confused? Read on for more (confusion).

Why Did?

Did methods like componentDidMount and componentDidUpdate are “safe”.
They fire after React finishes its work. So your futzing won’t collide with React’s futzing.

Use Did methods are first choice.

Why not Did?

Sometimes Dids don’t do exactly what you need.

In our Pokemon component, using componentDidUpdate will fetch and setState with a new Pokemon with each update. That sounds like what we want but isn’t.

New props update Pokemon but so does the setState calls. Infinite loops, run!!!

🏃‍♂️ 🏃‍♀️ 🏃‍♂️ 🏃‍♀️

We have one of those “unless you shouldn’t” cases.

Enter componentWillReceiveProps

We need a hero lifecycle method that fires for new props but not new state. componentWillReceiveProps is that hero.

componentWillReceiveProps(nextProps) {
  fetchPokemon(nextProps.id).then(character =>
    this.setState({ character: character })
  )
}

This lifecycle method fires before this.props is set to the new props. So we don’t use this.props. We use the nextProps, which componentWillReceiveProps receives as an argument.

💥

You’re just gonna have to play with this one…

Tinker with it

Use the workspace below and explore componentWillReceiveProps.

  • Compare this.props and nextProps by logging them.
    • Change the local name of nextProps. There’s nothing special about the name.
  • Read the docs. Any other things componentWillReceiveProps can do?