Reputation: 744
I know we are not supposed to mutate a state object directly. Does this apply to the state object available in the call back of setState
. I am looking to avoid using the spread operator too much. For example, can we do the following
setState(prevState => {
prevState.count += 1;
prevState.data.list[0].item.prop = 34;
return prevState;
});
Upvotes: 0
Views: 65
Reputation: 10382
you should always make copies from objects you modify to update state, otherwise you will face bugs in your application since you have the same reference. Each part of state you modify you should make a copy, which in really nested states could be difficult.
One thing advisable is to flat your state if you can. This way you avoid really nested states, which would lead to multiple copies and prone to error. Your example, it looks you could have 2 different states count
and items
:
const [count, setCount] = useState(0);
const [items, setItems] = useState(dataItems);
// some update state function logic call
setCount(count => ++count);
setItems(items => {
const nextItems = [...items]; // new arrray copy
nextItems[0] = { ...nextItems[0], prop: 34}; // new copy obj
return nextItems;
});
otherwise your state update would look like:
setState(prevState => {
const nextState = { ...prevState }
nextState.count += 1;
nextState.data = { ...nextState.data }
nextState.data.list = [ ...nextData.data.list ]
const item = nextState.data.list[0]
nextState.data.list[0].item = { ...nextState.data.list[0].item , prop: 34 };
return nextState;
});
Upvotes: 1