score:2
As you have said, yes, the general rule of thumb is "if the next state depends on the previous state, use an updater function."
is there anything wrong with [
this.setState({ regions: this.state.regions.map(...) })
]?
I think it depends on what's in the regions
array and what you pass to map()
. Maybe the best way to answer that question is to ask yourself if a batched update would cause problems:
const mapFcn = ...
const newState = Object.assign(
{},
{ regions: this.state.regions.map(mapFcn) },
{ regions: this.state.regions.map(mapFcn) },
);
In some cases this may not be a problem. If each region is a string, mapFcn = (region) => region.toUpperCase()
probably wouldn't cause any issues.
If regions
is an array of objects and mapFcn
does something like the "classic" increment example ((region) => ({ ...region, count: region.count + 1 })
), that might be a problem.
score:0
The state takes some time to be updated and it is not a good practice to perform an action on the state immediately after setting it. This makes reading this.state right after calling setState() a potential pitfall. If at all it is required, you can use the callback function that is called once the state is successfully updated. Here is the link to the documentation: https://reactjs.org/docs/react-component.html#setstate
score:0
There's nothing wrong with calling setState
multiple times with object updaters if the updates are not conflicting:
// works
setState({score: this.state.score + 1})
setState({players: [...this.state.players, 'Jack']})
If the updates are conflicting, the previous state should not be taken from this.state
, but rather setState
will supply it to you in the function updater:
// works
setState((prevState)=> ({score: prevState + 1}));
setState((prevState)=> ({score: prevState + 1}));
Both of these work fine.
What's wrong is just calling setState
with the object updater if you depend on the current state, even if it's just one call:
// does not work right
setState({
score: this.state.score + 1,
victory: this.state.score === 5 // this will be true one "turn/goal" later than expected
});
score:0
If you only set it one time it doesn't matter. But here's a super quick way to see why updater functions are preferred when you depend on the existing state when updating the state.
function incrementCounter1(){
this.setState({ counter: this.state.counter + 1 })
}
function incrementCounter2(){
this.setState(prevState => {
return {counter: prevState.counter + 1 }
})
}
Lets say the execution of setState()
is delayed by 1 second.
Within that 1 second you call incrementCounter1()
3 times.
Each time this.state.counter
is still 0, and setState()
receives {counter: 1}
.
Hence, the final value of counter is 1 - which is wrong.
Now if within 1 second you call incrementCounter2()
3 times, the function within setState()
is not invoked until React is ready to process the state change and previous state changes have been executed. Therefor, the prevState
object will always have the latest state. Hence the final value of counter is 3 - which is correct!
Source: stackoverflow.com
Related Query
- React setState based on the current state
- setState in React based on current state
- React setState componentDidUpdate React limits the number of .. when trying to update the state based on updated state
- Why does calling react setState method not mutate the state immediately?
- react setState callback doesn't have the updated state
- Append array of values to the current array in a state in React JS
- Change state dynamically based on the external Internet connectivity - React (offline/online)
- React State update a nested array with objects based on the id when iterated
- How to know if all the setState updates have been applied to the state in a React component?
- Should I organize my react redux reducer composition based on the calls made OR based on the state a reducer manages?
- React save the value of current state and make it unchangeable
- React setState not changing the state
- React DnD useDrop is not using the current state when the method is called
- Set the value of a form based on state in React
- How can I set the default state of a checkbox based on value in firestore in react table
- Change React component visibility based on the state of another component
- call react component in loop based on onclick button function which sets the state to true once button is clicked
- Style sheet to be imported based on the current active component in a multi-page React app with React-Router
- console.log this.state is not showing the current state in react
- When accessing the current state inside a React Hook's setState() call, is the prevState variable a copy or a direct reference to the state object?
- Change the state based on the previous state with React Hooks
- React JS: previousState in setState is not keeping the data of the previous state after the state is updated
- setState on React is setting my state only on the 2nd+ iteration
- How to keep the current state of a page after a refresh? - React
- React cannot set state inside useEffect does not update state in the current cycle but updates state in the next cycle. What could be causing this?
- in React i need to get the state from local storage and then set another state conditionally based on this state
- React setstate not merging the old state into the new state
- React hooks - setState is not updating the state properties to show sidebar
- React setState doesn't update the state after submitting input form
- How to transform the inner state based React app to Redux based?
More Query from same tag
- I am not able to change the state when I send an input by using a form
- React Hooks: useState with onClick only updating the SECOND time button is clicked?
- How do I update "read" to true in all the children of messages in firebase database
- React is very slow when I put button to every cells in hundred rows
- How to update single value inside array in redux
- How to use reduce to calculate the total amount in React component?
- Cannot import local fonts with TypeScript
- Javascript Reference function from fat arrow function, or how to trigger function every X sec
- I cant get Redux action to work there is some error I cant spot please advice
- Data lost in switch case reactjs
- How to filter a list according to Slider selection?
- How to map an array of object
- Adding custom fonts in react webpack packaging
- format number in react input
- What is the second parameter for in a React functional component?
- onClick this returning undefined in React
- How to mark an item completed with Redux?
- React Router V4 Get Current Path
- Cannot change the background colour of <SideNav>
- Is this correct way to render according to the state data using async await?
- action redux is undefined, did not get the data
- Could not find "store" in the context of "Connect(Items)". Either wrap the root component in a <Provider> in react.js?
- How to get the id of the added item after a post request in react?
- Karma gives me a __karma__.start adapter error without any other error
- React Hooks Remove item from array
- React Multiple Loading state
- Access data from props to render basic table with React, Typescript, Axios, hooks, Material.ui basic table structure
- How to override .MuiSelect-nativeInput in Material-UI
- Converting class to function React Error invalid hook call
- Axios IE 11 issue, cannot download response type blob