--- title: redux-toolkit update state in slice tags: Redux --- # redux-toolkit update state in slice Using **createSlice** with @redux-toolkit - As createSlice creates your actions as well as your reducer for you, you don't have to worry about type safety here. Action types can just be provided inline: Two apporach get same result: - Redux Toolkit ==mutable== (redux-toolkit only) - Redux ==immutable== (regular way) ## Redux immutable vs Redux-toolkit mutable :::info #### What Is Immutability? - First off, immutable is the opposite of mutable – and mutable means changeable, modifiable… able to be messed with. - So something that is immutable, then, is something that cannot be changed. ::: ### Redux immutable - Redux requires reducer functions to be pure and treat state values as immutable. ### Redux-toolkit mutable - Redux Toolkit allows us to write "mutating" logic in reducers. It doesn't actually mutate the state because it uses the [Immer](https://immerjs.github.io/immer/) library, which detects changes to a "draft state" and produces a brand new immutable state based off those changes. - Redux Toolkit's createReducer and createSlice automatically use Immer internally to let you write simpler immutable update logic using "mutating" syntax. This helps simplify most reducer implementations. ## mutable and immutable example > CreateSlice structure export const userSlice = createSlice({ name: 'user', initialState: { settings: { customTopics: { topicsSortType: { id: 1, name: '更改日期', order: 'incr' } } }, }, reducers: { changeTopicsSortType: (state, action) => { // example bellow }, } }); ### Redux Toolkit mutable (redux-toolkit only) changeTopicsSortType: (state, action) => { state.settings.customTopics.topicsSortType.id = action.payload.id; state.settings.customTopics.topicsSortType.name = action.payload.name; }, ### Redux immutable (regular way) changeTopicsSortType: (state, action) => { return { ...state, settings: { customTopics: { topicsSortType: { ...state.settings.customTopics.topicsSortType, id: action.payload.id, name: action.payload.name } } } }; }, --- Reference: - https://redux-toolkit.js.org/usage/usage-with-typescript#createslice - https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns - https://redux-toolkit.js.org/tutorials/quick-start#create-a-redux-state-slice - https://redux-toolkit.js.org/usage/immer-reducers - https://daveceddia.com/react-redux-immutability-guide/