React Lifecycle Methods — Updating

Photo by Gary Bendig on Unsplash

A component is updated whenever there is a change in state or props. These methods are called in the following order when updating a component on the DOM:

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

What is happening with each method?

The getDerivedStateFromProps() method is the first method that is called when a component gets updated. It is called upon right before the render method, both on the initial mount and on consecutive updates. This method is for rare use cases where state depends on changes in props over time.

The shouldComponentUpdate() method is invoked before rendering when new props or state are being received. This method is not called during the initial render. The shouldComponentUpdate() method returns a boolean value that specifies whether React should continue with rendering or not. The default value is true. It let’s React know if a components output is not affected by the current change in state or props. This method exists as a performance optimization and shouldn’t be relied on to prevent rendering because this can lead to bugs.

The render() method is called when a component gets updated, it re-renders the new changes to the DOM.

The getSnapShotBeforeUpdate() is called right before the most recently rendered content is committed to the DOM. With this method you have access to the props and state before the update, so even after the update, you can check what the values were before the update. This is another method that isn’t commonly used but in the react docs it says that it may occur in UIs like chat threads that require a method to handle scroll position.

The componentDidUpdate() is called immediately after the component updated to the DOM. This method isn’t called for initial render. This method is a good opportunity to manipulate the DOM when the component has been updated.


Lifelong Learner