JS Built-ins
redux-toolkitcreateSlicebeginner

Slice Action Creators

πŸ“– Usage Example
const { createSlice } = ReduxToolkit
const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    addBy: (state, action) => state + action.payload,
  },
})
counterSlice.actions.addBy(5) // β†’ { type: 'counter/addBy', payload: 5 }

Each reducer in createSlice becomes an action creator. The argument you pass becomes action.payload.

Slice Action Creators

createSlice automatically generates action creators. Each reducer key becomes an action creator that produces { type: 'sliceName/reducerName', payload: arg }.

Challenge: Create a counter slice with:

  • increment: increases count by 1
  • decrement: decreases count by 1
  • addBy(amount): adds the given amount
counterSlice.actions.addBy(5).payload // β†’ 5
counterSlice.reducer(3, addBy(7))     // β†’ 10
πŸ’‘ Hints (3)
  • β€’ Reducers that return a new value instead of mutating work fine too: `state => state + 1`.
  • β€’ The first argument to the payload creator is automatically set as `action.payload`.
  • β€’ Destructure `counterSlice.actions` to get named action creators.