Search⌘ K
AI Features

Creating Reducers with createReducer

Explore how to create readable and efficient reducers using Redux Toolkit's createReducer helper. Understand map object notation, direct state mutation with Immer, and default case handling to simplify managing state changes in Redux.

Creating reducers with createReducer

Of all Redux main actors, reducers getS the worst rap. Everyone seems to have something against them. From the widely annoying switch statements to the immutability constraints you have to employ, it’s easy to see why.

Well, let’s see what RTK’s has to offer to cure some of these woes.

The createReducer helper function, as you may have guessed, helps you write reducers with ease. Let’s explore its basic API.

Consider the Flappy reducer:

Javascript (babel-node)
export const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case updateCatMood.type:
return { ...state, mood: action.payload };
default:
return state;
}
};

This is a standard reducer creation set up, but the main goal of a reducer is to take in actions and return a new state while handling defaults and initial state.

With createReducer, a map object notation may be used as follows:

Javascript (babel-node)
const reducer = createReducer(initialState, actionsMap)

actionsMap is an ...