0
votes

I'm trying to understand the working of Redux functions, I'm able to understand how we create the Redux store and apply middleware.

While creating Redux store, we pass the rootReducers, preloadedState, storeEnhancer.

But in this code, I'm not able to understand how the resultant enhancer from compose function is given as input to the createStore function.

import thunk from 'redux-thunk'
import rootReducers from './reducers'
let finalCreateStore = compose(
    applyMiddleware(thunk),
    window.devToolsExtension ? window.devToolsExtension() : f => f
)(createStore)

export default function configureStore(initialState) {
    return finalCreateStore(rootReducers, initialState)
}
1

1 Answers

2
votes

Both applyMiddleware and window.devToolsExtension functions return a "store enhancer", meaning a function of the form createStore => createStore.
Each one of them expects to get a createStore function and returns a new one, which adds some functionality to the newly created store.

The code could be written without compose as:

let finalCreateStore = createStore;

const devToolsStoreEnhancer = window.devToolsExtension ? window.devToolsExtension() : f => f;
finalCreateStore = devToolsStoreEnhancer(finalCreateStore);

const middlewareStoreEnhancer = applyMiddleware(thunk);
finalCreateStore = middlewareStoreEnhancer(finalCreateStore);

Notice that compose applies the layers from last to first, so the order is reversed: https://redux.js.org/api/compose

Now finalCreateStore is a function with a similar signature to the original createStore, but contains two layers of enhancers above it. You can now create your store with a code like this:

const store = finalCreateStore(rootReducer, initialState);

When you call finalCreateStore(...) those layers create the store for you and add middleware and devtools support to it.

Hope it helps :)