Splitting Reducers for Code-Splitting
Demonstrate how to divide reducers and use injectReducer function to dynamically code split and load parts of the Redux store on demand.
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
// Initial root reducer
const staticReducers = {
// Static reducers here (reducers that are always present)
}
// Configure store with static reducers
export function configureStore(initialState) {
const store = createStore(
createReducer(),
initialState,
applyMiddleware(thunk)
);
// Add a dictionary to keep track of the registered async reducers
store.asyncReducers = {};
// Create an inject reducer function
// This function adds the async reducer, and replaces the existing reducer
store.injectReducer = (key, asyncReducer) => {
store.asyncReducers[key] = asyncReducer;
store.replaceReducer(createReducer(store.asyncReducers));
};
return store;
}
// Create the root reducer with both static and async reducers
function createReducer(asyncReducers) {
return combineReducers({
...staticReducers,
...asyncReducers
});
}
This code sets up the Redux store and provides the 'injectReducer' function that will be used to add new reducers dynamically to the store.
// Assume that we are in a React component file
import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
// A sample async reducer
const sampleReducer = (state = {}, action) => { /* reducer implementation */ };
const MyComponent = () => {
// Using Redux dispatch
const dispatch = useDispatch();
useEffect(() => {
const injectReducer = require('./pathToConfigureStore').injectReducer;
// Injecting the reducer when the component mounts
injectReducer('sample', sampleReducer);
}, [dispatch]);
// Component JSX
return (
// ...
);
};
export default MyComponent;
This code snippet should be placed in a React component file. It demonstrates how to use the 'injectReducer' method from the store to dynamically load a reducer when the component mounts.