A Resettable Reducer


When a redux powered react app starts to grow there is a comon use case: The need to reset a reducer’s state on specific events. Of course, handling the event in a new case inside the reducer returning its initial state is the obvious way to go.

But when the reducer is a combinedReducer, Having to edit each one of its aggregated reducers to makes them handle the reset event is a tedious and error prone process. One could easily forget to update one of them, now or during a future refactor.

One solution is to use the following Higher order reducer:

const (...resetOn) => reducer => (state, action) => {
  if (resetOn.includes(action.type) {
    return reducer(undefined, action);
  }
  return reducer(state, action);
}

A reducer is a simple function deriving a state from an action. By forcing a call with undefined as its current state when the action’s type is one we want to reset on, the reducer will return its initialState.

A simple use is the following one:

const resettableReducer = resettable(
'FIRST_TYPE', 'SECOND_TYPE'
)(originalReducer);