updating lifecycle methods

This is a continuation of the previous post regarding the React lifecycle components. The remaining lifecycle methods can be categorized under updating and unmounting. When a component is initially rendered, it does not update. A component will then update after each subsequent render.

There are four methods that help handle updates. In order, they are:

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • componentDidUpdate()

These methods will always be called in this order. The render() method, which renders the React component into the DOM, will be called just before componentDidUpdate().

When a component instance updates componentWillReceiveProps() gets called before the rendering begins. This method is called when the component is receiving new props from it’s parent. This method gets passed an argument, an object called nextProps, which is a preview of the upcoming props object that the component is about to receive. Just because the method is called doesn’t necessarily mean that the props have changed.

shouldComponentUpdate()automatically receives two arguments, nextProps and nextState, and returns a boolean. The return value is used to determine whether the component should update or not.

The next method, componentWillUpdate(), is called immediately after the check in shouldComponentUpdate() has passed. No state changes are allowed in this method and it is used for preparing for the upcoming update, not to trigger one. It can be used to call an action, set a variable, interact with an API, or any other event based on state changes.

The previous methods run just before the render()method. componentDidUpdate() gets passed two arguments, prevProps and prevState. These are references to the component’s props and state before the current updating period began and are compared to the current props and state. It is typically used for any DOM updates following a render, like interacting with 3rd party libraries.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.