hdavidzhu hdavidzhu - 1 year ago 149
Javascript Question

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

When I

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

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

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

Edit #2: I started with
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 Source

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.