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.
If we don't use React, then we can't expect our application to reflect any changes that we made to the state. In other words, if we update state with plain JavaScript and not setState , it will not trigger a re-render and React will not display those (invalid) changes in state to our user.
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With