Configuring Your Store

In the basics section, we introduced the fundamental Redux concepts by building an example Todo list app.

We will now explore how to customise the store to add extra functionality. We'll start with the source code from the basics section, which you can view in the documentation, in our repository of examples, or in your browser via CodeSandbox.

Creating the store

First, let's look at the original index.js file in which we created our store:

  1. import React from 'react'
  2. import { render } from 'react-dom'
  3. import { Provider } from 'react-redux'
  4. import { createStore } from 'redux'
  5. import rootReducer from './reducers'
  6. import App from './components/App'
  7. const store = createStore(rootReducer)
  8. render(
  9. <Provider store={store}>
  10. <App />
  11. </Provider>,
  12. document.getElementById('root')
  13. )

In this code, we pass our reducers to the Redux createStore function, which returns a store object. We then pass this object to the react-redux Provider component, which is rendered at the top of our component tree.

This ensures that any time we connect to Redux in our app via react-redux connect, the store is available to our components.

Extending Redux functionality

Most apps extend the functionality of their Redux store by adding middleware or store enhancers (note: middleware is common, enhancers are less common). Middleware adds extra functionality to the Redux dispatch function; enhancers add extra functionality to the Redux store.

We will add two middlewares and one enhancer:

  • The redux-thunk middleware, which allows simple asynchronous use of dispatch.
  • A middleware which logs dispatched actions and the resulting new state.
  • An enhancer which logs the time taken for the reducers to process each action.

Install redux-thunk

  1. npm install --save redux-thunk

middleware/logger.js

  1. const logger = store => next => action => {
  2. console.group(action.type)
  3. console.info('dispatching', action)
  4. let result = next(action)
  5. console.log('next state', store.getState())
  6. console.groupEnd()
  7. return result
  8. }
  9. export default logger

enhancers/monitorReducer.js

  1. const round = number => Math.round(number * 100) / 100
  2. const monitorReducerEnhancer = createStore => (
  3. reducer,
  4. initialState,
  5. enhancer
  6. ) => {
  7. const monitoredReducer = (state, action) => {
  8. const start = performance.now()
  9. const newState = reducer(state, action)
  10. const end = performance.now()
  11. const diff = round(end - start)
  12. console.log('reducer process time:', diff)
  13. return newState
  14. }
  15. return createStore(monitoredReducer, initialState, enhancer)
  16. }
  17. export default monitorReducerEnhancer

Let's add these to our existing index.js.

  • First, we need to import redux-thunk plus our loggerMiddleware and monitorReducerEnhancer, plus two extra functions provided by Redux: applyMiddleware and compose.

  • We then use applyMiddleware to create a store enhancer which will apply our loggerMiddleware and the thunkMiddleware to the store's dispatch function.

  • Next, we use compose to compose our new middlewareEnhancer and our monitorReducerEnhancer into one function.

This is needed because you can only pass one enhancer into createStore. To use multiple enhancers, you must first compose them into a single larger enhancer, as shown in this example.

  • Finally, we pass this new composedEnhancers function into createStore as its third argument. Note: the second argument, which we will ignore, lets you preloaded state into the store.
  1. import React from 'react'
  2. import { render } from 'react-dom'
  3. import { Provider } from 'react-redux'
  4. import { applyMiddleware, createStore, compose } from 'redux'
  5. import thunkMiddleware from 'redux-thunk'
  6. import rootReducer from './reducers'
  7. import loggerMiddleware from './middleware/logger'
  8. import monitorReducerEnhancer from './enhancers/monitorReducer'
  9. import App from './components/App'
  10. const middlewareEnhancer = applyMiddleware(loggerMiddleware, thunkMiddleware)
  11. const composedEnhancers = compose(
  12. middlewareEnhancer,
  13. monitorReducerEnhancer
  14. )
  15. const store = createStore(rootReducer, undefined, composedEnhancers)
  16. render(
  17. <Provider store={store}>
  18. <App />
  19. </Provider>,
  20. document.getElementById('root')
  21. )

Problems with this approach

While this code works, for a typical app it is not ideal.

Most apps use more than one middleware, and each middleware often requires some initial setup. The extra noise added to the index.js can quickly make it hard to maintain, because the logic is not cleanly organised.

The solution: configureStore

The solution to this problem is to create a new configureStore function which encapsulates our store creation logic, which can then be located in its own file to ease extensibility.

The end goal is for our index.js to look like this:

  1. import React from 'react'
  2. import { render } from 'react-dom'
  3. import { Provider } from 'react-redux'
  4. import App from './components/App'
  5. import configureStore from './configureStore'
  6. const store = configureStore()
  7. render(
  8. <Provider store={store}>
  9. <App />
  10. </Provider>,
  11. document.getElementById('root')
  12. )

All the logic related to configuring the store - including importing reducers, middleware, and enhancers - is handled in a dedicated file.

To achieve this, configureStore function looks like this:

  1. import { applyMiddleware, compose, createStore } from 'redux'
  2. import thunkMiddleware from 'redux-thunk'
  3. import monitorReducersEnhancer from './enhancers/monitorReducers'
  4. import loggerMiddleware from './middleware/logger'
  5. import rootReducer from './reducers'
  6. export default function configureStore(preloadedState) {
  7. const middlewares = [loggerMiddleware, thunkMiddleware]
  8. const middlewareEnhancer = applyMiddleware(...middlewares)
  9. const enhancers = [middlewareEnhancer, monitorReducersEnhancer]
  10. const composedEnhancers = compose(...enhancers)
  11. const store = createStore(rootReducer, preloadedState, composedEnhancers)
  12. return store
  13. }

This function follows the same steps outlined above, with some of the logic split out to prepare for extension, which will make it easier to add more in future:

  • Both middlewares and enhancers are defined as arrays, separate from the functions which consume them.

This allows us to easily add more middleware or enhancers based on different conditions.

For example, it is common to add some middleware only when in development mode, which is easily achieved by pushing to the middlewares array inside an if statement:

  1. if (process.env.NODE_ENV === 'development') {
  2. middlewares.push(secretMiddleware)
  3. }
  • A preloadedState variable is passed through to createStore in case we want to add this later.

This also makes our createStore function easier to reason about - each step is clearly separated, which makes it more obvious what exactly is happening.

Integrating the devtools extension

Another common feature which you may wish to add to your app is the redux-devtools-extension integration.

The extension is a suite of tools which give you absolute control over your Redux store - it allows you to inspect and replay actions, explore your state at different times, dispatch actions directly to the store, and much more. Click here to read more about the available features.

There are several ways to integrate the extension, but we will use the most convenient option.

First, we install the package via npm:

  1. npm install --save-dev redux-devtools-extension

Next, we remove the compose function which we imported from redux, and replace it with a new composeWithDevTools function imported from redux-devtools-extension.

The final code looks like this:

  1. import { applyMiddleware, createStore } from 'redux'
  2. import thunkMiddleware from 'redux-thunk'
  3. import { composeWithDevTools } from 'redux-devtools-extension'
  4. import monitorReducersEnhancer from './enhancers/monitorReducers'
  5. import loggerMiddleware from './middleware/logger'
  6. import rootReducer from './reducers'
  7. export default function configureStore(preloadedState) {
  8. const middlewares = [loggerMiddleware, thunkMiddleware]
  9. const middlewareEnhancer = applyMiddleware(...middlewares)
  10. const enhancers = [middlewareEnhancer, monitorReducersEnhancer]
  11. const composedEnhancers = composeWithDevTools(...enhancers)
  12. const store = createStore(rootReducer, preloadedState, composedEnhancers)
  13. return store
  14. }

And that's it!

If we now visit our app via a browser with the devtools extension installed, we can explore and debug using a powerful new tool.

Hot reloading

Another powerful tool which can make the development process a lot more intuitive is hot reloading, which means replacing pieces of code without restarting your whole app.

For example, consider what happens when you run your app, interact with it for a while, and then decide to make changes to one of your reducers. Normally, when you make those changes your app will restart, reverting your Redux state to its initial value.

With hot module reloading enabled, only the reducer you changed would be reloaded, allowing you to change your code without resetting the state every time. This makes for a much faster development process.

We'll add hot reloading both to our Redux reducers and to our React components.

First, let's add it to our configureStore function:

  1. import { applyMiddleware, compose, createStore } from 'redux'
  2. import thunkMiddleware from 'redux-thunk'
  3. import monitorReducersEnhancer from './enhancers/monitorReducers'
  4. import loggerMiddleware from './middleware/logger'
  5. import rootReducer from './reducers'
  6. export default function configureStore(preloadedState) {
  7. const middlewares = [loggerMiddleware, thunkMiddleware]
  8. const middlewareEnhancer = applyMiddleware(...middlewares)
  9. const enhancers = [middlewareEnhancer, monitorReducersEnhancer]
  10. const composedEnhancers = compose(...enhancers)
  11. const store = createStore(rootReducer, preloadedState, composedEnhancers)
  12. if (process.env.NODE_ENV !== 'production' && module.hot) {
  13. module.hot.accept('./reducers', () => store.replaceReducer(rootReducer))
  14. }
  15. return store
  16. }

The new code is wrapped in an if statement, so it only runs when our app is not in production mode, and only if the module.hot feature is available.

Bundlers like Webpack and Parcel support a module.hot.accept method to specify which module should be hot reloaded, and what should happen when the module changes. In this case, we're watching the ./reducers module, and passing the updated rootReducer to the store.replaceReducer method when it changes.

We'll also use the same pattern in our index.js to hot reload any changes to our React components:

  1. import React from 'react'
  2. import { render } from 'react-dom'
  3. import { Provider } from 'react-redux'
  4. import App from './components/App'
  5. import configureStore from './configureStore'
  6. const store = configureStore()
  7. const renderApp = () =>
  8. render(
  9. <Provider store={store}>
  10. <App />
  11. </Provider>,
  12. document.getElementById('root')
  13. )
  14. if (process.env.NODE_ENV !== 'production' && module.hot) {
  15. module.hot.accept('./components/App', renderApp)
  16. }
  17. renderApp()

The only extra change here is that we have encapsulated our app's rendering into a new renderApp function, which we now call to re-render the app.

Simplifying Setup with Redux Starter Kit

The Redux core library is deliberately unopinionated. It lets you decide how you want to handle everything, like storesetup, what your state contains, and how you want to build your reducers.

This is good in some cases, because it gives you flexibility, but that flexibility isn't always needed. Sometimes wejust want the simplest possible way to get started, with some good default behavior out of the box.

The Redux Starter Kit package is designed to help simplify several common Redux use cases, including store setup.Let's see how it can help improve the store setup process.

Redux Starter Kit includes a prebuilt configureStore function likethe one shown in the earlier examples.

The fastest way to use is it is to just pass the root reducer function:

  1. import { configureStore } from 'redux-starter-kit'
  2. import rootReducer from './reducers'
  3. const store = configureStore({
  4. reducer: rootReducer
  5. })
  6. export default store

Note that it accepts an object with named parameters, to make it clearer what you're passing in.

By default, configureStore from Redux Starter Kit will:

  • Call applyMiddleware with a default list of middleware, including redux-thunk, and some development-only middleware that catch common mistakes like mutating state
  • Call composeWithDevTools to set up the Redux DevTools Extension
    Here's what the hot reloading example might look like using Redux Starter Kit:
  1. import { configureStore, getDefaultMiddleware } from 'redux-starter-kit'
  2. import monitorReducersEnhancer from './enhancers/monitorReducers'
  3. import loggerMiddleware from './middleware/logger'
  4. import rootReducer from './reducers'
  5. export default function configureAppStore(preloadedState) {
  6. const store = configureStore({
  7. reducer: rootReducer,
  8. middleware: [loggerMiddleware, ...getDefaultMiddleware()],
  9. preloadedState,
  10. enhancers: [monitorReducersEnhancer]
  11. })
  12. if (process.env.NODE_ENV !== 'production' && module.hot) {
  13. module.hot.accept('./reducers', () => store.replaceReducer(rootReducer))
  14. }
  15. return store
  16. }

That definitely simplifies some of the setup process.

Next Steps

Now that you know how to encapsulate your store configuration to make it easier to maintain, you can learn more about the advanced features Redux provides, or take a closer look at some of the extensions available in the Redux ecosystem.