Blog>
Snippets

Dynamic Middleware Injection in Redux 5.0.0

Illustrative code for dynamically injecting middlewares at runtime in Redux 5.0.0, allowing for more flexible and modular store configuration.
// First, we set up the basic store with redux and apply the initial middleware
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
let store;

function configureStore(initialState = {}) {
  const middlewares = [];
  store = createStore(
    rootReducer,
    initialState,
    applyMiddleware(...middlewares)
  );
  return store;
}

// Adding a function to inject middlewares dynamically
function injectMiddleware(...newMiddlewares) {
  const currentMiddlewares = store.getMiddlewares();
  const allMiddlewares = [...currentMiddlewares, ...newMiddlewares];
  store.replaceMiddleware(applyMiddleware(...allMiddlewares));
}

// Usage
const store = configureStore();
injectMiddleware(someMiddleware);
This code block demonstrates how to set up a Redux store and a function that allows you to dynamically inject new middleware into the store at runtime.