Blog>
Snippets

Resetting State with createReducer

Provide a code example illustrating the pattern for resetting the state to its initial value using createReducer within Redux Toolkit.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Define an action to reset the state
const resetState = createAction('state/reset');

// Define the initial state
const initialState = {
  value: 0
  // ... other state values
};

// Create a reducer using the initial state and a builder callback
const exampleReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(resetState, () => initialState) // Handle reset state action
    // ... other action handlers
});

export default exampleReducer;
This code creates a reducer with Redux Toolkit that handles a 'resetState' action. When this action is dispatched, the state is reset to its initial value. 'createAction' is used to define the reset action, and 'createReducer' receives a builder callback which specifies the reset action handling by returning 'initialState'.