Blog>
Snippets

Dynamic Injection of Reducers with combineSlices API

Give an example of dynamically injecting reducers into the store using the new combineSlices API to facilitate code splitting and improve application scalability.
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';

// Dynamic Combine Slices
function combineSlices(asyncSlices) {
  return combineReducers({
    ...asyncSlices
  });
}

// Configure and create the store
const store = configureStore({
  reducer: combineSlices({}) // initially no slices
});

// An example of adding a new slice dynamically
export function injectReducer(key, asyncReducer) {
  store.asyncReducers[key] = asyncReducer;
  store.replaceReducer(combineSlices(store.asyncReducers));
}

// Usage
// import { injectReducer } from './store';
// import someAsyncSliceReducer from './features/someAsyncSlice';
// injectReducer('someAsyncSlice', someAsyncSliceReducer);
This code sets up a configured store with an initially empty set of reducers. It provides a function 'injectReducer' for injecting new reducers dynamically. Once you have a new slice reducer, you call 'injectReducer' passing the slice name and the reducer function. Note that the combineSlices API presented in the references does not actually exist in Redux Toolkit; the combination logic is typically handled by 'combineReducers' from Redux directly or using 'configureStore' from Redux Toolkit, which automatically combines the reducers.