Code Splitting
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 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:
Now, one just needs to call to add a new reducer to the store.
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 remove a reducer, one can now call store.reducerManager.remove("asyncState")
There are a few good libraries out there that can help you add the above functionality automatically:
- :Provides tools for building dynamic Redux stores, including dynamically adding reducers and sagas, and React bindings to help you add in association with components.
- :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-thunk
andredux-saga
which also help dynamically load their artifacts (thunks, sagas).