I have an array of objects which I want to loop through and reset the selected
value for each item to false
:
// Amount data state
const [amountData, setAmountData] = useState([
{
id: 30,
amount: (30000).toLocaleString(),
selected: true,
},
{
id: 10,
amount: (10000).toLocaleString(),
selected: true,
},
{
id: 70,
amount: (70000).toLocaleString(),
selected: true,
},
{
id: 50,
amount: (50000).toLocaleString(),
selected: true,
},
]);
What I was wondering is if the correct way of updating the state in setState
is to loop through the current state directly (amountData
) or loop through the prevState
and if either way would have any benefit over the other method?
Using state
directly:
// Reset selection
setAmountData(
amountData.map(amount => {
return {
...amount,
selected: false,
};
}),
);
Using prevState
:
// Reset selection
setAmountData(prevState =>
prevState.map(amount => {
return {
...amount,
selected: false,
};
}),
);
3
Answers
It’s recommended to use the
prevState
when updating state based on the previous state in React. Because React state updates may be asynchronous, and if you rely on the current state directly, you might end up with stale or incorrect state values.Using
prevState
ensures that you’re always working with the most up-to-date state values when making updates.So you should use
prevState
which is safer and guarantees that you’re working with the correct state values when updating theamountData
state.You really only need to use the
setState(prevState => ...)
synthax if you have multiplesetState
calls in a row.There is no recommendation to always use this synthax, it’s a matter of preference. See https://react.dev/reference/react/useState#is-using-an-updater-always-preferred
As mentioned in the React docs , if you just pass on the next state’s value to a setState, and have multiple such setStates in your handler, all of them get batched, and only one gets applied to your state value.
However, passing a function that takes the prevState, and applies changes to the state variable based on whatever that value is, does not cause this batching.
In your case, since you only have setState once, both the methods yield the same result.
I have gone ahead and created a sandbox where you can experiment with my code and look at the console to better understand this.