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?
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.
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.
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.
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.
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