Reputation: 856
Lets imagine a simple reducer:
const [state, setState] = React.useReducer(myReducer, {})
And myReducer
with one single case (simplified version):
const myReducer = (state, action) => {
switch (action.type) {
case 'UPDATE_STATE': {
// Code to update here...
}
}
}
Now, which of the following statements is best suited to update a state - and why:
NOTE: payload
= state
.
METHOD 1
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object = true
return updatedState
}
METHOD 2
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object= true
return { ...state, updatedState }
}
METHOD 3
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object= true
return { ...state, ...updatedState }
}
METHOD 4
case 'UPDATE_STATE': {
return ({ ...state, object: true })
}
Upvotes: 1
Views: 82
Reputation: 20441
I think you should Use method 4. You are not mutating the state here, which is the React way.
case 'UPDATE_STATE': {
return ({ ...state, object: true })
}
Note: Spread operator ...
creates different references up to one level only.
EDIT: Based on comments, here is a simple example of how you could be mutating state, even with the simplest of objects if you are not using ...
.
let state = { object : true};
let payload = state;
state.object = false;
console.log(state);
console.log(payload);
Even with ...
you might have deeply nested objects. They will have the same problem, unless you want to spread at every level. There are libraries to help you with deep objets like immutable.js.
Upvotes: 1