One rule of reducer in Redux is: we should treat state as read-only, and return a new object as the new state.
But there is one grey area: must it strictly return a new object as state, or can we return the same state object?
It seems by looking at common code, such as:
function favoriteColors(state, action) {
if (state === undefined) {
state = [];
}
if (action.type === 'ADD') {
return Array.from(new Set([...state, action.color])); // new array
} else if (action.type === 'REMOVE') {
return state.filter(color => color !== action.color); // new array
} else {
return state;
}
}
When the action.type
is unknown, then the same state object is returned. So the rule is that the reducer doesn't strictly have to return a new state object, but can return the same one. But the strict rule is that the state must be read-only?