React React Component Lifecycle Component Update


Example

componentWillReceiveProps(nextProps)

This is the first function called on properties changes.

When component's properties change, React will call this function with the new properties. You can access to the old props with this.props and to the new props with nextProps.

With these variables, you can do some comparison operations between old and new props, or call function because a property change, etc.

componentWillReceiveProps(nextProps){
  if (nextProps.initialCount && nextProps.initialCount > this.state.count){
    this.setState({
      count : nextProps.initialCount
    });
  }
}

shouldComponentUpdate(nextProps, nextState)

This is the second function called on properties changes and the first on state changes.

By default, if another component / your component change a property / a state of your component, React will render a new version of your component. In this case, this function always return true.

You can override this function and choose more precisely if your component must update or not.

This function is mostly used for optimization.

In case of the function returns false, the update pipeline stops immediately.

componentShouldUpdate(nextProps, nextState){
  return this.props.name !== nextProps.name ||
    this.state.count !== nextState.count;
}

componentWillUpdate(nextProps, nextState)

This function works like componentWillMount(). Changes aren't in DOM, so you can do some changes just before the update will perform.

/!\ : you cannot use this.setState().

componentWillUpdate(nextProps, nextState){}

render()

There's some changes, so re-render the component.

componentDidUpdate(prevProps, prevState)

Same stuff as componentDidMount() : DOM is refreshed, so you can do some work on the DOM here.

componentDidUpdate(prevProps, prevState){}