Sub topic 5
Creating the store with configureStore
This chapter assumes you can write a slice with createSlice and know that a reducer is a pure function of (state, action). It also assumes you know what an action is. Here you build the store that holds your slice reducers and see what configureStore adds beyond plain Redux.
What the store is
The store is the single object that holds your application state. It does four things:
- It keeps the current state tree.
- It runs your root reducer when you call
dispatch(action). - It lets you read the state with
getState(). - It notifies listeners registered with
subscribe(listener)after each dispatch.
Plain Redux has a createStore function for this. It is deprecated. Redux Toolkit (RTK) provides configureStore, which builds the same store but also sets up middleware, development checks and DevTools support for you.
The minimal store
You pass configureStore an object with a reducer field. If that field is an object, each key becomes a top-level key in the state, and RTK combines the reducers with Redux's combineReducers for you.
import { configureStore, createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1
},
},
})
const { incremented } = counterSlice.actions
const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
})
store.subscribe(() => {
console.log('state changed:', store.getState())
})
console.log('initial:', store.getState())
store.dispatch(incremented())Running this prints initial: { counter: { value: 0 } }, then state changed: { counter: { value: 1 } }. The key counter in the reducer object decides the state path. Reading state.counter.value works because of that key, not because of the slice's name.
You can also pass a single reducer function instead of an object. That is useful when you build the root reducer yourself, but the object form is the normal choice.
What configureStore sets up
Compared with createStore, configureStore does the following in one call:
- Combines the reducer object into a root reducer.
- Builds a middleware chain from a default set.
- Connects the store to the Redux DevTools Extension.
- Applies the middleware and any enhancers.
The block above is a placeholder only. See the diagram below.
Default middleware
Middleware is code that sits between dispatch and the reducer. It can inspect, delay, change or block actions. The default chain contains:
| Middleware | Runs in | Purpose |
|---|---|---|
| thunk | all builds | Lets you dispatch functions, which `createAsyncThunk` relies on |
| immutability check | development | Throws if a reducer or other code mutates state outside Immer |
| serializability check | development | Warns if state or actions contain values such as functions, Promises, Maps or class instances |
| action creator check | development | Warns if you pass an action creator where an action was expected, such as `dispatch(incremented)` |
In production builds only the thunk middleware remains, so the checks cost nothing there. This is why a mistake can show up in development and never appear in a production bundle.
Customizing middleware
To add your own middleware, use the callback form of the middleware option and extend the defaults with concat. This keeps thunk and the checks in place.
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
const logger = (storeApi) => (next) => (action) => {
console.log('dispatching', action.type)
const result = next(action)
console.log('next state', storeApi.getState())
return result
}
export const store = configureStore({
reducer: { counter: counterReducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(logger),
})The logger has three nested functions. The outer one receives the store API (dispatch and getState), the middle one receives next, which passes the action along the chain, and the inner one receives the action. Always return the result of next(action), because the return value of dispatch depends on it.
Order matters. Middleware runs in array order for the way in, so getDefaultMiddleware().concat(logger) places the logger after the defaults. Use prepend instead if your middleware must see actions first.
Tuning the built-in checks
Sometimes a check flags something you have chosen to allow. You can configure each check by passing options to getDefaultMiddleware.
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
export const store = configureStore({
reducer: { counter: counterReducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: ['persist/PERSIST'],
ignoredPaths: ['session.startedAt'],
},
immutableCheck: { warnAfter: 64 },
}),
})ignoredActions and ignoredPaths silence the serializability warning for specific actions or state paths. warnAfter sets how many milliseconds the immutability check may take before it logs a warning. Both are better than switching a check off with serializableCheck: false, because a narrow exception keeps the protection for everything else.
Preloaded state
The preloadedState option sets the initial state of the store. This is how you hydrate state from server-side rendering or from saved storage.
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
export const store = configureStore({
reducer: { counter: counterReducer },
preloadedState: { counter: { value: 10 } },
})
console.log(store.getState())This prints { counter: { value: 10 } }. The keys in preloadedState must match the keys in your reducer object. Any slice you leave out falls back to its own initialState.
DevTools and enhancers
The devTools option defaults to true in development and false when NODE_ENV is production. You can pass an options object to give the store a name or limit how many actions DevTools keeps.
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
export const store = configureStore({
reducer: { counter: counterReducer },
devTools: { name: 'My app', maxAge: 50 },
})An enhancer is a function that wraps the whole store creation process and can change how the store behaves. Most apps never write one. When you need to add one, use the enhancers callback in the same style as middleware: enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(myEnhancer).
Where the store lives
Create the store in one module and export it. Components do not import it directly. You pass it to Provider, which the next chapter covers. Outside React, in a utility or in tests, you may import it and call store.dispatch or store.getState. Avoid that inside components, because it bypasses the hooks that trigger re-renders.
A store should be created once per app instance. If you render on the server, create a new store for each request. A module-level store would otherwise share state between users.
Common errors
- A reducer returns
undefined. Redux throws when a reducer returnsundefined. Return the state (or a new value) from every branch. WithcreateSlicethis mostly happens when you writereturnwith no value in an arrow function. - A mutation warning from the immutability check. The message names the path that changed. It usually means you modified state inside a selector, a component or a plain function, outside a
createSlicereducer. Copy the data first. - A serializability warning. You put a
Date, a function or a class instance into an action or into state. Store an ISO string or a timestamp, or add a narrow ignore as shown above. dispatch(incremented)does nothing. You passed the action creator, not the action. Call it:dispatch(incremented()). The action creator check warns about this in development.- State keys that do not match.
state.counterisundefinedbecause the reducer key iscount. Check thereducerobject keys and your selectors.
Exercise
A teammate writes middleware: () => [logger] in configureStore so that every action is logged. Afterwards, dispatching a createAsyncThunk action fails and the development warnings about mutations disappear. What went wrong, and how do you fix it?
Show answer
The callback returns only logger, so it replaces the default middleware chain. That removes the thunk middleware, which createAsyncThunk needs, and it also removes the immutability and serializability checks. Fix it by extending the defaults: middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger).
Exercise
You create a store with reducer: { counter: counterReducer } and preloadedState: { counter: { value: 10 }, todos: { items: [] } }. What is the problem with this configuration?
Show answer
preloadedState contains a todos key, but the reducer object has no todos reducer. Redux warns about the unexpected key and ignores it. Add a todos reducer to the reducer object, or remove the key from preloadedState.