Replacing the Reducer

Learn how to replace the reducer during runtime.

When creating the Redux store, a reducer function (often referred to as the root reducer) is passed as the first parameter to createStore().

We can use the store’s replaceReducer() method to replace this reducer function. Usually, this method is used in development to allow hot replacement of reducers. It might be used to dynamically decorate or replace the root reducer in complex applications to allow code splitting.

Code splittingseparating the production bundle into multiple files and loading them on demand when the user performs some interaction or visits a specific route is common when the application is too large to bundle into a single file or when you want to gain extra performance. Implementing lazy loading is outside the scope of this course, but you might want to know that code splitting also can be applied to the Redux store, thanks to the replaceReducer() method.

Let’s look at a simple example with some functionality available only for authenticated users. At initial load, our store will only handle the currentUser substate enough for the authentication:

import { combineReducers } from 'redux';
import { currentUser } from 'reducers/current-user';

const reducer = combineReducers({ currentUser });

const store = createStore(reducer);

Note: The combineReducers() function is discussed in detail later.

After the user signs in, we load the new functionality. We need to make sure our store is aware of the new subset of our application state and the function that should handle it. Here is where the replaceReducer() method comes in handy:

const newReducer = combineReducers({ currentUser, recipes });

store.replaceReducer(newReducer);

Keep in mind that when you call replaceReducer(), Redux automatically calls the same initial action it calls when you first create the store, so your new reducer automatically gets executed. The new state is immediately available via the store.getState() method.

Get hands-on with 1200+ tech skills courses.