Order of Execution

The example below illustrates the order of the different React lifecycle methods.

Notice how updating the state in componentDidMount() triggers shouldComponentUpdate(), and later render(). If shouldComponentUpdate() were to return false, the output will have been 1 | 2 10 | 3 | 4 20 | 2 30 | 5 | 8.
RESETRUNFULL
class Demo extends React.Component {
    constructor(props) {
      super(props);
      this.state = {x:10};
      console.log(1);
   }
   componentDidMount() {
      console.log(4,this.state.x);
      this.setState({x:30});
   }
   shouldComponentUpdate() {
      console.log(5);
      return true;
   }
   getSnapshotBeforeUpdate(prevProps, prevState){
      console.log(6,prevState.x,this.state.x);
      return 999;
   }
   componentDidUpdate(prevProps, prevState, snapshot) {
      console.log(7,snapshot);
   }
   componentWillUnmount() {
      console.log(8);
   }
   static getDerivedStateFromProps(props, state){  // always called before render()
      console.log(2,state.x);
      return {x:20};    // the new state to be updated
   }
   render() {
      console.log(3);
      return null;
   }}ReactDOM.render(
   <Demo />,
   document.querySelector('div'));ReactDOM.unmountComponentAtNode(document.querySelector('div'));

In general, avoid updating 'state' in render() as it will probably cause an infinite loop. It should be initialized in constructor() and generally updated in componentDidMount().

Beware that if we execute an asynchronous request (such as an AJAX fetch()) in the constructor, it may be resolved out-of-order. Try fetching data in componentDidMount() instead (5.3).