Store Enhancers
Learn about the store enhancers that help decorate the store.
Store enhancers are higher-order functions used to enhance the default behavior of the Redux store. In contrast to middleware and reducers, they have access to all internal store methods.
To give a few examples, there are store enhancers for:
- Store synchronization (between browser tabs or even network clients)
- State persistence
- Integration with developer tools
Let’s build an example store enhancer that will persist state changes and load the initial state from localStorage
. To enhance or decorate a store, we need to write a higher-order function that receives the original store factory function as a parameter and returns a function similar in signature to createStore()
:
import { createStore } from 'redux';
import { rootReducer } from 'reducers/root';
const persistStore = (next) =>
(reducer, initialState, enhancer) => {
let store;
if (typeof initialState !== 'function') {
store = next(reducer, initialState, enhancer);
} else {
const preloadedState = initialState ||
JSON.parse(localStorage.getItem('@@PersistedState') || {})
store = next(reducer, preloadedState, enhancer);
}
store.subscribe(() => localStorage.setItem(
'@@PersistedState',
JSON.stringify(store.getState())
));
return store;
}
Get hands-on with 1400+ tech skills courses.