hdavidzhu hdavidzhu - 6 months ago 81
Javascript Question

How do I update the state (using ReactJS) if I should not call setState in componentWillUpdate?

When I

setState
in
componentWillUpdate
,
componentWillUpdate
runs in an infinite loop that doesn't stop getting triggered.

This never gives my
render
a chance to reflect my changes. How can I change the state if I shouldn't use
componentWillUpdate
?

Edit: I already have some understanding that
setState
should not be called in componentWillUpdate. I'm just confused what I should do as an alternative.

Edit #2: I started with
componentWillReceiveProps
but I can't seem to trigger this function when my Parent component changes state. I provide that state from the parent as a props to my child.

Answer

First thing to do is to check official documentation for this method (link). Where you can read when the function is actually called.

Then read common mistake(note):

You cannot use this.setState() in this method. If you need to update state in response to a prop change, use componentWillReceiveProps instead.

You change the state and React automatically calls componentWillUpdate.