In large web applications, it is often desirable to split up the app code into multiple JS bundles that can be loaded on-demand. This strategy, called 'code splitting', helps to increase performance of your application by reducing the size of the initial JS payload that must be fetched.
To code split with Redux, we want to be able to dynamically add reducers to the store. However, Redux really only has a single root reducer function. This root reducer is normally generated by calling
combineReducers() or a similar function when the application is initialized. In order to dynamically add more reducers, we need to call that function again to re-generate the root reducer. Below, we discuss some approaches to solving this problem and reference two libraries that provide this functionality.
The Redux store exposes a
replaceReducer function, which replaces the current active root reducer function with a new root reducer function. Calling it will swap the internal reducer function reference, and dispatch an action to help any newly-added slice reducers initialize themselves:
Reducer Injection Approaches
We will likely want to call
store.replaceReducer() from anywhere in the application. Because of that, it's helpful
to define a reusable
injectReducer() function that keeps references to all of the existing slice reducers, and attach
that to the store instance.
Now, one just needs to call
store.injectReducer to add a new reducer to the store.
Using a 'Reducer Manager'
Another approach is to create a 'Reducer Manager' object, which keeps track of all the registered reducers and exposes a
reduce() function. Consider the following example:
To add a new reducer, one can now call
To remove a reducer, one can now call
Libraries and Frameworks
There are a few good libraries out there that can help you add the above functionality automatically:
redux-dynostore: Provides tools for building dynamic Redux stores, including dynamically adding reducers and sagas, and React bindings to help you add in association with components.
redux-dynamic-modules: This library introduces the concept of a 'Redux Module', which is a bundle of Redux artifacts (reducers, middleware) that should be dynamically loaded. It also exposes a React higher-order component to load 'modules' when areas of the application come online. Additionally, it has integrations with libraries like
redux-sagawhich also help dynamically load their artifacts (thunks, sagas).
- Redux Ecosystem Links: Reducers - Dynamic Reducer Injection