CodeBlanks Logo Icon CodeBlanks

Slice

Learn state slices with createSlice.

createSlice

createSlice is RTK's most important function. A slice is an object containing name, initialState and reducers. RTK automatically generates an action creator and action type for each function in reducers. This removes the need for separate files.

Example: const counterSlice = createSlice({ name: 'counter', initialState: 0, reducers: { increment: (state) => state + 1 } }). counterSlice.actions.increment is an action creator; counterSlice.reducer is the reducer itself. A slice keeps a piece of state and the functions that change it together.

The reducers field

The reducers object lists the functions that change state. Each function takes two parameters: state and action. RTK uses the immer library so it looks like you can mutate state directly; under the hood it still does an immutable update.

Example: increment: (state) => state + 1 or addBy: (state, action) => state + action.payload. In the second example action.payload carries the value sent during dispatch. RTK wraps this function into an action creator that you can call as addBy(value).

Practice Write the counterSlice

Complete the empty file. Import createSlice from @reduxjs/toolkit. Define counterSlice: name: 'counter', initialState: 0, reducers: { increment: (state) => state + 1, decrement: (state) => state - 1 }. Add export default counterSlice.reducer and export const { increment, decrement } = counterSlice.actions.

Starter code

App.js
import { createSlice } from '@reduxjs/toolkit';

// define counterSlice and export

Sample solution

App.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    decrement: (state) => state - 1,
  },
});

export default counterSlice.reducer;
export const { increment, decrement } = counterSlice.actions;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the slice name

Question
createSlice({
  name: '____',
  initialState: 0,
  reducers: {}
})
Answer
createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {}
})

Explanation: counter is the slice name.

2 Match the slice parts

Term Meaning
name Slice name
initialState Initial value
reducers Mutating functions
actions Action creators

3 What does createSlice produce?

  • Both a reducer and action creators
  • Only a reducer Correct answer
  • Only a store
  • Only a style

Explanation: createSlice produces both a reducer and action creators.

All lessons in Advanced