JS Built-ins
redux-toolkitcreateSlicebeginner

Create Slice Basics

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

createSlice bundles the reducer and action creators together β€” no need to write action type constants manually.

createSlice Basics

createSlice is the recommended way to write Redux logic. It generates action creators and action types automatically based on the reducer names you provide.

Challenge: Create a counter slice with:

  • name: 'counter'
  • initialState: { value: 0 }
  • one reducer increment that increases value by 1
counterSlice.name // β†’ 'counter'
counterSlice.actions.increment().type // β†’ 'counter/increment'
πŸ’‘ Hints (3)
  • β€’ Use `createSlice({ name, initialState, reducers })` to define your slice.
  • β€’ With Immer inside createSlice, you can write `state.value += 1` directly in a reducer.
  • β€’ The action creator is automatically created as `counterSlice.actions.increment`.