4

I was following this guide on LifeCycle Methods in React & I tweaked a demo in that guide a little bit like https://codesandbox.io/s/m7m4qz6pqp

It is a simple app which uses all React's new lifecycle methods & adds Grids to the bottom every 10 seconds (so wait for 10 seconds & then see the console).

The way I understand getDerivedStateFromProps is they get called when the parent props change but in this sandbox if you check the console, it gets called even when the props aren't changed.

I've added some helpful console.log's tracing the order.

Right now, it shows this in the Console

getDerivedStateFromProps - 1, 4 
render - 2, 6 
render - 2
componentDidMount - 3 
getDerivedStateFromProps - 1, 4 

This means

getDerivedStateFromProps gets called 1st due to 1, 4 render gets called 2nd due to 2, 6 render of Error component gets called after that which we can ignore componentDidMount gets called 3rd due to 3 getDerivedStateFromProps gets called 4th due to 1, 4

Now I understand every other order. I just didn't understand why getDerivedStateFromProps is called the 4th time 1, 4.

Can anyone explain why this happens as I am not seeing any props change after 1st time?

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163

1 Answers1

2

Firstly in version of React 16.3, getDerivedStateFromProps() just was invoked when updating props(http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/). But now in version of React 16.4, getDerivedStateFromProps() is invoked when updating props and updating state (regardless of the reason for re-rendering). So in your condition,

getDerivedStateFromProps() is invoked before render() method under that conditions;

  1. Initial mount
  2. Every state and prop updating

Your component will be rendered every blocks update in per 10 sec and getDerivedStateFromProps() will invoked in every 10 sec consequently.

sdkcy
  • 3,528
  • 1
  • 16
  • 23