Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Redux Toolkit

createAction and createReducer

Learn Redux Toolkit's createAction (with prepare callbacks and match) and createReducer (builder addCase, addMatcher, addDefaultCase), the building blocks beneath createSlice, with runnable stand-ins.

createSlice is built from two smaller helpers: createAction, which makes an action creator from a type string, and createReducer, which makes a reducer from a list of cases. You will often use createSlice alone, but these two matter in several situations: you need an action that does not belong to one slice, you want several slices to react to the same action, you migrate old Redux code, or you need matchers that handle groups of actions.

createAction, createReducer and isAnyOf are exports of @reduxjs/toolkit, so real code here is read-only. The runnable examples use short stand-ins with the same API shapes (and the copy-then-reuse produce stand-in from Immer in Reducers).

createAction

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

export const loggedOut = createAction('auth/loggedOut');
export const todoAdded = createAction('todos/added');

loggedOut();           // { type: 'auth/loggedOut', payload: undefined }
todoAdded('Buy milk'); // { type: 'todos/added', payload: 'Buy milk' }

The result is an action creator function with useful extras:

Feature Use
todoAdded.type The type string 'todos/added'. Also what toString() returns.
todoAdded.match(action) A type guard: true if the action was made by this creator.
Used as an object key { [todoAdded]: ... } works because of toString().

Because of .match, you can test an action without comparing strings: if (todoAdded.match(action)) { ... }.

Prepare callbacks

By default the first argument becomes payload. A prepare callback lets you take any arguments and build payload, meta and error yourself, which is where ids and timestamps belong (so the reducer stays pure):

JavaScript
const todoAdded = createAction('todos/added', (text) => ({
  payload: { id: crypto.randomUUID(), text, createdAt: Date.now() },
}));

todoAdded('Buy milk');
// { type: 'todos/added', payload: { id: '3f2a...', text: 'Buy milk', createdAt: 1731400000000 } }

The same callback shape works inside createSlice, as { reducer, prepare }. Try both features with a stand-in:

JS createAction with prepare and match

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

No output.

createReducer

createReducer(initialState, builderCallback) builds a reducer without a switch. Inside the callback you describe cases with the builder:

JavaScript
import { createAction, createReducer } from '@reduxjs/toolkit';

const incremented = createAction('counter/incremented');
const added = createAction('counter/added');

const counterReducer = createReducer({ value: 0 }, (builder) => {
  builder
    .addCase(incremented, (state) => {
      state.value += 1;
    })
    .addCase(added, (state, action) => {
      state.value += action.payload;
    });
});

Like createSlice, createReducer uses Immer, so case reducers may "mutate" the draft or return a new value. The builder has three methods; call them in this order, as the order is checked:

  1. addCase(actionCreatorOrType, reducer): handle one exact action. Add all of these first.
  2. addMatcher(predicate, reducer): handle every action for which predicate(action) returns true.
  3. addDefaultCase(reducer): run if nothing else matched. If you skip it, unmatched actions return the state unchanged.

How matching works

For each action Redux Toolkit runs: the matching addCase reducer (if any), then every matcher that returns true (in the order you added them), or the default case if none ran. The results chain: each reducer receives the state produced by the previous one.

JS addCase, addMatcher and addDefaultCase

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

No output.

Notice that added triggers both its own case reducer and the matcher (changes goes up), and that a matched action never reaches the default case. The store's own init action matched nothing, which is why unknown starts at 1 (a real store dispatches an init action too). isAnyOf(a, b) and isAllOf(...) build predicates from action creators. Matchers are also how you handle all of a thunk's pending/fulfilled/rejected actions in groups, something you will use in the async chapter.

createSlice or createReducer?

Use When
createSlice The default. It owns state and creates the actions that belong to it.
createAction An action that several slices respond to, or that no slice owns (app/reset, auth/loggedOut).
createReducer A reducer that only listens to actions defined elsewhere, or a migration of a legacy switch reducer.
addMatcher Shared handling for many actions at once (all rejected thunks, every action with meta.error).

Common pattern: define the shared action with createAction in its own file, import it into every slice that needs it, and listen with extraReducers (see createSlice). That avoids circular imports between slice files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does todoAdded.match(action) return?

    match is a predicate (a type guard in TypeScript) that tells you whether an action was created by that creator.
  2. 2. What is a prepare callback for?

    prepare returns { payload, meta, error }. Impure values are created there so the reducer stays pure.
  3. 3. In which order must you call the createReducer builder methods?

    All addCase calls come first, then addMatcher calls, then at most one addDefaultCase. Toolkit throws if the order is wrong.
  4. 4. When is the default case reducer executed?

    The default case is the fallback for actions nothing else matched.

Summary

  • createAction(type, prepare?) returns a creator with .type, .match and toString().
  • Prepare callbacks build payload and meta, keeping ids and timestamps out of reducers.
  • createReducer(initial, builder) uses addCase, then addMatcher, then addDefaultCase; Immer works inside.
  • Matching reducers chain: the case reducer first, then each matching matcher, or the default if nothing ran.
  • Use createSlice by default; reach for these helpers for shared actions, matchers and legacy migration.

Next: Provider and the React-Redux Hooks