Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 934
dot_zero Avatar asked Mar 09 '15 14:03

dot_zero


People also ask

Can we update state without setState?

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.

Why do you need to use setState () to update state in React?

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.

Can we update the state in React directly?

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.

What is the proper way to update the state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.


1 Answers

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.

like image 81
zaynetro Avatar answered Oct 05 '22 07:10

zaynetro