Extract complex case reducers
A slice has many reducers and inline definitions make the createSlice call hard to read.
Redux Toolkit · Type Alias
CaseReducer is a TypeScript function type for describing a reducer that handles a particular state and action shape. Define one outside createSlice when inline reducers become difficult to manage or when reuse is useful.
CaseReducer is a TypeScript type for a reducer function that handles one action shape. It lets you define reusable case reducers outside createSlice and type their state and action explicitly.
CaseReducer<State, Action>| Name | Type | Description |
|---|---|---|
state | State | The current state value handled by the case reducer; its type is supplied by the first generic parameter. |
action | Action | The dispatched action handled by the case reducer; its type is supplied by the second generic parameter. |
The next state value, or an Immer-compatible case-reducer result when used through Redux Toolkit reducer APIs.
import type { CaseReducer, PayloadAction } from '@reduxjs/toolkit'
type State = number
const increment: CaseReducer<State, PayloadAction<number>> = (state, action) =>
state + action.payload
console.log(increment(1, { type: 'increment', payload: 2 }))A typed case reducer receives the current state and an action, then returns the next state.
A slice has many reducers and inline definitions make the createSlice call hard to read.
The same state transition belongs to multiple slices or reducer definitions.
A reducer needs explicit state and payload typing outside a slice declaration.
CaseReducer is a TypeScript type used to describe an individual reducer function. It is useful when a case reducer is declared outside createSlice, especially when the reducer should be reused or separately typed.
Follow-up: Why can a separately declared case reducer be preferable to an inline one? It keeps large slice definitions easier to read and allows the reducer to be reused across slices.
The state type is supplied as the first generic argument, and the action type is supplied as the second. The reducer then receives state and action with those types.
Follow-up: How can action typing be inferred in builder.addMatcher? Use a type-predicate matcher, which narrows the action argument for the reducer callback.
A case reducer handles one action shape and calculates the next state. In Redux Toolkit, case reducers are used by APIs such as createSlice and createReducer.
Follow-up: What makes Redux Toolkit reducer code appear mutable? createSlice and createReducer use Immer internally, allowing draft updates that produce immutable state.
createSlicecreateReducerPayloadActionActionReducerMapBuilderbuilder.addMatcher