Redux ~ Code splitting - rohit120582sharma/Documentation GitHub Wiki

A Redux store's state tree is created from a single reducer function. combineReducers is the mechanism to compose many reducer functions into a single reducer that can be used to build a hierarchical the state tree. It is not possible to modify the reducer function after the store has been initialised.

redux-dynamic-reducer library allows you to attach new reducer functions after the store is initialised. This is helpful if you want to use a single global store across a lazily loaded application where not all reducers are available at store creation.

This library will help if you want to lazily load and execute pieces of your application but still manage your state in a global store. It allows Redux modules to be loaded on-demand, without requiring all Redux modules to be bundled in the main chunk for the store to correctly initialize.

Limitations

  • Each dynamic reducer needs a unique key. If the same key is used in a subsequent attachment, the original reducer will be replaced.
  • Nested reducers cannot be attached to nodes of the state tree owned by a static reducer.

Install

$ npm install --save redux-dynamic-reducer


Getting start

Create the store

The createStore function replaces the Redux createStore function. It adds the attachReducers() function to the store object. The createStore function also supports all of the optional parameters that the built-in Redux createStore function does:

import { combineReducers, applyMiddleware } from 'redux';
import { createStore } from 'redux-dynamic-reducer';
...
const rootReducer = combineReducers({
	staticReducer1,
	staticReducer2
});
const store = createStore(rootReducer, applyMiddleware(middleware))

Add a dynamic reducer

The store now has a new function on it caller attachReducers to attach dynamic reducers to the store at runtime:

store.attachReducers({
	'newReducer1': dynamicReducer1,
	'newReducer2': dynamicReducer2
});

Reducers can also be added to nested locations in the store:

store.attachReducers({
	'some.path.to': {'uniqueKeyName': dynamicReducer}
})


Custom Implementation

store.replaceReducer

The store already has a method which allows us to swap in a new reducer, to which we can pass an object with new keys, representing the reducers that have been dynamically loaded.

addNewReducer has two responsibilities. First, store all dynamic reducers in asyncReducers. This ensures that each time we invoke addNewReducer we don’t lose other dynamic reducers. Next, call replaceReducer which is Redux in-build API.

store.asyncReducers = {};
store.addNewReducer = (newModuleInfo) => {
	store.asyncReducers[newModuleInfo.name] = newModuleInfo.reducer;

	store.replaceReducer(combineReducers({
		app: rootReducer,
		...asyncReducers
	}));
}
⚠️ **GitHub.com Fallback** ⚠️