JS Built-ins
redux-toolkitcreateSlicebeginner

Immer Mutations in Reducers

πŸ“– Usage Example
const { createSlice } = ReduxToolkit
const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo(state, action) { state.push(action.payload) },
  },
})

Immer lets you mutate the draft state directly β€” createSlice handles the immutable update behind the scenes.

Immer Mutations in Reducers

createSlice uses Immer under the hood, so you can write "mutating" code that is actually applied immutably. You can push, splice, or assign properties directly.

Challenge: Create a todos slice where:

  • addTodo pushes a todo to the array
  • removeTodo removes a todo by id
todosSlice.reducer([], addTodo({ id: 1, text: 'buy milk' }))
// β†’ [{ id: 1, text: 'buy milk' }]
πŸ’‘ Hints (3)
  • β€’ Use `state.push(action.payload)` to add β€” Immer makes this safe.
  • β€’ For removeTodo, returning a new array with `filter` also works alongside Immer.
  • β€’ The initial state `[]` is typed as an array, so push and filter are available.