InterviewHubPRO
Section Overview
Q420

Question 420 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

94%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

What is the methods order when component re-rendered?

An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered.

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

Code Example

tsx
import React, { Component } from 'react';

class UpdateOrderTracker extends Component<{ count: number }> {
  // 1. static getDerivedStateFromProps(props, state)
  static getDerivedStateFromProps(props: any, state: any) {
    console.log('1. static getDerivedStateFromProps');
    return null;
  }

  // 2. shouldComponentUpdate(nextProps, nextState)
  shouldComponentUpdate(nextProps: any, nextState: any) {
    console.log('2. shouldComponentUpdate');
    return true;
  }

  // 3. render()
  render() {
    console.log('3. render');
    return <div>Current Count: {this.props.count}</div>;
  }

  // 4. getSnapshotBeforeUpdate(prevProps, prevState)
  getSnapshotBeforeUpdate(prevProps: any, prevState: any) {
    console.log('4. getSnapshotBeforeUpdate');
    return { scrollPos: 120 };
  }

  // 5. componentDidUpdate(prevProps, prevState, snapshot)
  componentDidUpdate(prevProps: any, prevState: any, snapshot: any) {
    console.log('5. componentDidUpdate with snapshot:', snapshot);
  }
}