Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 41 ยท Redux Toolkit

createSlice in Redux Toolkit

Learn createSlice: name, initialState, reducers, generated actions, extraReducers for other slices' actions, prepare callbacks and slice selectors. Includes runnable stand-ins and the real API.

createSlice is the function you will use most in Redux Toolkit. You describe one slice of state (a name, its initial value and the ways it can change) and Toolkit gives you back a reducer and a matching set of action creators. One declaration replaces action types, action creators and the switch statement.

createSlice needs @reduxjs/toolkit, so real examples below are read-only. The runnable ones use a clearly labelled stand-in for createSlice (including extraReducers, prepare and selectors) plus a copy-then-reuse stand-in for Immer's produce.

Anatomy of a slice

JavaScript
// needs @reduxjs/toolkit (read-only here)
import { createSlice } from '@reduxjs/toolkit';

const todosSlice = createSlice({
  name: 'todos',                       // prefix for action types
  initialState: { items: [], nextId: 1 },
  reducers: {
    added(state, action) {
      state.items.push({ id: state.nextId++, text: action.payload, done: false });
    },
    toggled(state, action) {
      const todo = state.items.find((t) => t.id === action.payload);
      if (todo) todo.done = !todo.done;
    },
    cleared(state) {
      state.items = [];
    },
  },
});

export const { added, toggled, cleared } = todosSlice.actions;
export default todosSlice.reducer;
  • name: a string used as the prefix of every generated action type. The reducer added produces todos/added.
  • initialState: the starting state. Make it a plain object with every key you need, so the shape is visible at a glance.
  • reducers: an object of case reducers. Each takes (state, action) and either mutates state (Immer makes this safe, see Immer in Reducers) or returns a new value.

What you get back is an object with, among others:

Property Meaning
todosSlice.reducer The reducer function to give to configureStore.
todosSlice.actions An object of action creators: added, toggled, cleared.
todosSlice.name 'todos'.
todosSlice.getInitialState() The initial state value.
todosSlice.selectors Selectors you defined, bound to the root state (see below).

An action creator takes one argument and puts it into action.payload: added('Buy milk') returns { type: 'todos/added', payload: 'Buy milk' }. Each creator also has a .type property and a .match(action) check.

A slice end to end

JS A todos slice with a stand-in createSlice

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exports: the convention

A slice file normally has three kinds of exports, as in the real code above:

  1. Action creators as named exports (export const { added, toggled } = slice.actions).
  2. The reducer as the default export (export default slice.reducer).
  3. Selectors as named exports (export const selectItems = (state) => state.todos.items).

You do not need to export the slice object. Components import actions and selectors; the store file imports the reducer.

One argument, one payload

An action creator accepts a single value. If you need several, pass an object:

JavaScript
dispatch(moved({ id: 4, x: 20, y: 35 }));

// in the slice
moved(state, action) {
  const { id, x, y } = action.payload;
  const item = state.byId[id];
  item.x = x;
  item.y = y;
},

When the payload needs computing (an id, a timestamp), use a prepare callback: write the reducer as an object with reducer and prepare functions. The details are in createAction and createReducer; here is the shape:

JavaScript
added: {
  reducer(state, action) {
    state.items.push(action.payload);
  },
  prepare(text) {
    return { payload: { id: crypto.randomUUID(), text, done: false } };
  },
},

Callers still write dispatch(added('Buy milk')); the unique id is created before the action reaches the reducer, so the reducer stays pure.

Responding to other slices' actions: extraReducers

reducers defines the actions the slice owns. To react to an action defined elsewhere (another slice, or an async thunk), use extraReducers with the builder callback. In Redux Toolkit 2 the builder callback is the only form (the old object form was removed).

JavaScript
import { createSlice } from '@reduxjs/toolkit';
import { loggedOut } from '../auth/authSlice';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: { /* ... */ },
  extraReducers: (builder) => {
    builder.addCase(loggedOut, () => ({ items: [] })); // reset the cart on logout
  },
});

The key difference: reducers creates actions (cart/added); extraReducers listens to existing ones and creates nothing. Run the pattern:

JS One action, two slices (extraReducers)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Slice selectors (RTK 2)

Since Redux Toolkit 2 a slice can hold its own selectors, written against the slice state and exposed in slice.selectors against the root state:

JavaScript
const todosSlice = createSlice({
  name: 'todos',
  initialState: { items: [] },
  reducers: { /* ... */ },
  selectors: {
    selectItems: (state) => state.items,
    selectOpenCount: (state) => state.items.filter((t) => !t.done).length,
  },
});

export const { selectItems, selectOpenCount } = todosSlice.selectors;
// useSelector(selectOpenCount)   <- receives the root state

The slice finds its own state by name (or reducerPath), so the selectors keep working wherever you mount the reducer, provided you use the same key as the name. Selectors that compute new arrays should be memoised (see useSelector).

Naming reducers

Name the keys in reducers as events in the past tense, the same advice you saw in Actions and Action Creators: added, toggled, cleared, filterChanged. The generated type todos/added reads like a log line. Avoid setter-style names like setItems or updateTodoState.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What action type does a reducer named 'incremented' in a slice named 'counter' produce?

    The type is sliceName/reducerName.
  2. 2. What does slice.actions.added('Milk') return?

    An action creator returns a plain action object. Its single argument becomes the payload.
  3. 3. When should you use extraReducers instead of reducers?

    reducers creates actions the slice owns. extraReducers listens to existing actions, for example from another slice or an async thunk.
  4. 4. In Redux Toolkit 2, how is extraReducers written?

    The object notation was removed in RTK 2; the builder callback gives better type inference.

Summary

  • createSlice({ name, initialState, reducers }) returns reducer and actions; types are name/reducerName.
  • Case reducers may "mutate" the draft state (Immer) or return a new value.
  • Action creators take one argument that becomes action.payload; use prepare for computed payloads.
  • extraReducers with the builder callback listens to actions the slice does not own.
  • RTK 2 slices can define selectors, exposed in slice.selectors for the root state.

Next: Immer in Reducers