Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevstate in `this.setState` -- a copy or a reference?

I've been trying to figure this out for a while and haven't come across the correct answer.

In the following code:

this.setState(prevState => counter: prevState.counter + 1);

is prevState a reference to the current state? Or is it a copy of it? Is it fine to mutate or should mutating it be avoided?

like image 951
JSilv Avatar asked Aug 10 '17 16:08

JSilv


People also ask

What is setState and prevState?

setState is the primary method used to update the UI in response to event handlers and server responses. prevState() is the same as the setState but the only difference between them is that if we want to change the state of a component based on the previous state of that component, we use this.

Why we use prevState in React?

Because for React to access the counter state, it should complete its rendering cycle. But, since we force React to read the counter state before the cycle completion, it's only referring to the last one.

Why is React not updating on state change?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.


1 Answers

From the documents...

prevState is a reference to the previous state. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from prevState and props.

https://facebook.github.io/react/docs/react-component.html

So to answer your question, prevState is the state before the last mutation occurred.

like image 179
Chris Hawkes Avatar answered Sep 21 '22 09:09

Chris Hawkes