Example for reducer changes the state
trajano opened this issue · 1 comments
trajano commented
What docs page needs to be fixed?
- Section: Define Slice State and Action Types
- Page: https://redux.js.org/usage/usage-with-typescript
What is the problem?
The example:
increment: state => {
state.value += 1
},
decrement: state => {
state.value -= 1
},
Changes the state which contradicts https://redux.js.org/style-guide/#do-not-mutate-state
What should be changed to fix the problem?
increment: state => ({
...state,
value: state.value + 1
}),
decrement: state => {
...state,
value: state.value - 1
},
phryneas commented
That example shows a Redux Toolkit createSlice
reducer.
Within those, you are allowed to (and probably even should) modify state
directly. See writing Reducers with immer
We show this because we officially recommend every Redux project (even pre-existing ones) should be using Redux Toolkit since 2019. See Why Redux Toolkit is how to use Redux today.
"Do not mutate state" still holds true if you are writing a reducer function by hand, but it is not true for case reducers, where createSlice
makes sure that. no matter if you write mutating or non-mutating code, no mutation actually takes place.