Blog>
Snippets

Dynamic addition of reducers at runtime

Explain how to dynamically inject a reducer into the Redux store at runtime using the `injectReducer` function provided by Redux Toolkit 2.0.
import { configureStore } from '@reduxjs/toolkit';

// Configure the initial store with an empty reducer object
const store = configureStore({
  reducer: {},
});

export default store;
Initializes the Redux store with an empty object for reducers. The store is configured using Redux Toolkit's configureStore function.
import store from './store';
import { createReducer, createAction } from '@reduxjs/toolkit';

// Define a simple action
const myAction = createAction('myAction');

// Define a dynamic reducer handling the above action
const myDynamicReducer = createReducer({}, {
  [myAction]: (state, action) => {
    // Handle the action
  }
});

// Function to inject a reducer into the store at runtime
function injectReducer(key, reducer) {
  if (Object.hasOwnProperty.call(store.asyncReducers, key)) return;
  store.asyncReducers[key] = reducer;
  store.replaceReducer(createReducer(store.asyncReducers));
}

// Inject the dynamic reducer
injectReducer('myDynamicKey', myDynamicReducer);
Defines a simple action and a dynamic reducer that handles this action using Redux Toolkit's createAction and createReducer. The injectReducer function injects the dynamic reducer into the existing store at runtime, using a key to identify the reducer. The new reducer is combined with any existing asynchronous reducers and replaced within the store using replaceReducer.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Reducer Injection</title>
    <script src="https://cdn.jsdelivr.net/npm/redux@4.0.5/dist/redux.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@1.6.1/dist/redux-toolkit.umd.min.js"></script>
    <script defer src="store.js"></script>
    <script defer src="dynamicReducerInjection.js"></script>
</head>
<body>
    <!-- Your HTML content goes here -->
</body>
</html>
Basic HTML document structure including the necessary Redux and Redux Toolkit scripts. It also includes defer attributes for custom script files 'store.js' and 'dynamicReducerInjection.js', which correspond to the previous code snippets.