Using Higher-Order Reducers
Learn how to use higher-order Reducers in Redux.
The power of Redux is that it allows you to solve complex problems using functional programming. One approach is to use higher-order functions. Since reducers are nothing more than pure functions
, we can wrap them in other functions and create very simple solutions for very complicated problems.
There are a few good examples of using higher-order reducers to implement undo/redo functionality. There is a library called redux-undo that takes your reducer and enhances it with undo functionality. It creates three substates: past, present, and future. Every time your reducer creates a new state, the previous one is pushed to the past states array, and the new one becomes the present state. You can then use special actions to undo, redo, or reset the present state.
Using a higher-order reducer is as simple as passing your reducer into an imported function:
import { combineReducers } from 'redux';
import recipesReducer from 'reducers/recipes';
import ingredientsReducer from 'reducers/ingredients';
import undoable from 'redux-undo';
// use undoable for the recipes Reducer
const rootReducer = combineReducers({
recipes: undoable(recipesReducer),
ingredients: ingredientsReducer
});
Another example of a reducer enhancer is redux-ignore. This library allows your reducers to return to the current state without handling the passed action immediately. Nor do reducers have to handle only a defined subset of actions. The following example will disable removing recipes from our recipe book. You might even use it to filter allowed actions based on user roles:
import { combineReducers } from 'redux';
import recipesReducer from 'reducers/recipes';
import ingredientsReducer from 'reducers/ingredients';
import { ignoreActions } from 'redux-ignore';
import { REMOVE_RECIPE } from 'constants/actionTypes';
const rootReducer = combineReducers({
recipes: ignoreActions(recipesReducer, [REMOVE_RECIPE]),
ingredients: ingredientsReducer
});
Get hands-on with 1400+ tech skills courses.