Blog>
Snippets

Best Practices for Redux Middleware Configuration

Presents exemplary code for configuring Redux middleware like Redux Thunk or Saga with Redux Toolkit to ensure optimal setup and application performance.
import { configureStore } from '@reduxjs/toolkit';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';

// Create the saga middleware
const sagaMiddleware = createSagaMiddleware();

// Configure the store with rootReducer, adding the sagaMiddleware and logger
const store = configureStore({
 reducer: rootReducer,
 middleware: (getDefaultMiddleware) =>
 getDefaultMiddleware()
 .prepend(sagaMiddleware) // Adding sagaMiddleware at the beginning of middleware chain
 .concat(logger), // Adding logger at the end of middleware chain
});

// Run the root saga
sagaMiddleware.run(rootSaga);

export default store;
This code creates a Redux store using Redux Toolkit's configureStore function. It includes the use of Redux-Saga as middleware for handling side effects, and Redux-Logger for logging actions. The sagaMiddleware is added at the beginning of the middleware chain while logger is added at the end. The rootSaga is then run using sagaMiddleware.run(rootSaga).