Blog>
Snippets

Reusing Reducer Logic with Action Generators

Demonstrate creating generic action generators with createAction and using them within multiple createReducer instances for handling similar state shapes.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Action Generators
const incrementBy = createAction('incrementBy');
const decrementBy = createAction('decrementBy');

// Reducer for counter1
const counter1Reducer = createReducer({ value: 0 }, (builder) => {
  builder
    .addCase(incrementBy, (state, action) => {
      state.value += action.payload;
    })
    .addCase(decrementBy, (state, action) => {
      state.value -= action.payload;
    });
});

// Reducer for counter2
const counter2Reducer = createReducer({ count: 0 }, (builder) => {
  builder
    .addCase(incrementBy, (state, action) => {
      state.count += action.payload;
    })
    .addCase(decrementBy, (state, action) => {
      state.count -= action.payload;
    });
});
Creates two action generators 'incrementBy' and 'decrementBy', and then uses them in two separate reducers 'counter1Reducer' and 'counter2Reducer'. Each reducer uses the same action generators to handle incrementing and decrementing its respective state piece by the action payload.