Redux: Difference between using compose() or applyMiddleware without it?

Viewed 985

I've had it like this before:

  createStore(reducers, {}, applyMiddleware(reduxThunk));

Just saw a different piece of code somewhere and now changed my code to this, using compose:

  createStore(reducers, {}, compose(applyMiddleware(reduxThunk)))

Both work fine so far. But I don't understand the difference exactly. Was what I had before wrong? Could someone explain this to me?

3 Answers

A "store enhancer" is a specific type of Redux addon that wraps around a store to give it extra abilities.

createStore accepts a single store enhancer as an argument, and uses that to customize the created store.

That means that if you want to use multiple store enhancers at once, you need a way to somehow combine them into a single store enhancer so you can pass it to createStore.

applyMiddleware is a store enhancer, so you can use it directly and pass its result as the one-and-only enhancer to createStore.

If you want to use multiple enhancers, like both applyMiddleware and devTools, you need to use compose() to combine them together.

Note that you should really be using our official Redux Toolkit package, which has a configureStore API that will already set up a Redux store correctly for you with one line of code.

@markerikson is right. Both of them work well.

  • If you are working on simple React app, the first one is enough.

  • If you handle large projects, you need to use the second one. Like below:

    const history = createHistory(); const sagaMiddleware = createSagaMiddleware(); const routeMiddleware = routerMiddleware(history); const middlewares = [thunk, sagaMiddleware, routeMiddleware];

    const composeEnhancers = (window['REDUX_DEVTOOLS_EXTENSION_COMPOSE'] as typeof compose) || compose;

    const store = createStore( combineReducers({ ...reducers, router: connectRouter(history), }), composeEnhancers(applyMiddleware(...middlewares)), );

From redux docs:

Tips All compose does is let you write deeply nested function transformations without the rightward drift of the code. Don't give it too much credit!

Also you can add some enhancements differ from thunk and middlewares. Check out this comment

Related