darKnight
darKnight

Reputation: 6481

Methods called after new state is set inside a React Component

So I am trying to understand the re-render lifecycle of React Components. Once setState is called, it re-renders the component. But what all life cycle methods will be called (in correct order) when re--rendering begins? Below diagram from Dan Abramov is helpful, but it doesn't throw much light on the re-rendering phase of a React component.

React LifeCycle Methods

If getDerivedStateFromProps returns a new state (thus 'setting' a new state like setState), does it cause re-rendering? If yes, won't the re-rendering cause getDerivedStateFromProps to be called again, causing an infinite loop (assuming there is no condition for props checking inside getDerivedStateFromProps)?

Upvotes: 2

Views: 1592

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Once setState is called, it re-renders the component. But what all life cycle methods will be called (in correct order) when re--rendering begins?

Once setState is called, that "period" is called Updating on the screen shot you gave (but updating can also happen for new props as shown on the image), hence you should refer to that part of the image - it also shows which method comes after which.

If yes, won't the re-rendering cause getDerivedStateFromProps to be called again, causing an infinite loop (assuming there is no condition for props checking inside getDerivedStateFromProps)?

No, it will not cause an infinite loop. Here is example to demo that. However, it seems in later versions of react (http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/), GDSFP is called even after setState, so you may want to double think if unconditionally returning new state from it is what you want.

Upvotes: 3

pixeline
pixeline

Reputation: 17974

getDerivedStateFromProps does not inherently set a new state like setState, and so, it does not cause re-rendering per se.

Quoting dave-ceddia in his book "Pure React":

static getDerivedStateFromProps(nextProps, prevState): This is an opportunity to change the state based on the value of props, which can be useful for initialization. It’s not used very frequently. Don’t call setState here, but instead, return an object that represents the new state. This method must not have side effects. Also, don’t forget the static keyword before this method or it won’t work. Since this method is static, you can’t access the this object.

Upvotes: 1

Related Questions