Blog>
Snippets

Enhancers and Middleware in Redux v5.0.0

Provide an example of how to combine enhancers with the new middleware approach in Redux v5.0.0.
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

// Define your own custom middleware
const customMiddleware = store => next => action => {
  // Your custom middleware logic here
  console.log('Custom Middleware:', action);
  return next(action);
};

// You might want to use Redux DevTools Extension
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// Combine middleware within the compose function
const enhancer = composeEnhancers(
  applyMiddleware(thunk, customMiddleware),
  // You can add more enhancers if you have them
);

// Create store with rootReducer and the combined enhancer
const store = createStore(
  rootReducer,
  enhancer
);

export default store;
This JavaScript code sets up a Redux store with both middleware (like redux-thunk and a custom middleware) and potentially other enhancers such as the Redux DevTools extension. The Redux store is created using `createStore` with the root reducer and an enhancer composed of the applied middleware and any additional enhancers.