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. It also assumes you have a React project with @reduxjs/toolkit and react-redux installed.
What the store does
The store is the single object that holds your app's state tree. It runs your reducers, keeps the current state, and notifies subscribers after each change. Plain Redux needs several calls to set one up. configureStore does that setup in one call and adds safety checks for development.
Building a store
Pass an object with a reducer field. If that field is an object of slice reducers, RTK combines them for you. Each key becomes a top-level key of the state.
import { configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1
},
},
})The snippet above is missing an import, so here is the complete version:
import { createSlice, configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1
},
amountAdded(state, action) {
state.value += action.payload
},
},
})
export const { incremented, amountAdded } = counterSlice.actions
export const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
})
console.log(store.getState())
// { counter: { value: 0 } }
store.dispatch(amountAdded(5))
console.log(store.getState())
// { counter: { value: 5 } }The key counter decides where the slice's state lives, so state.counter.value is the path selectors will use later.
What configureStore sets up
Beyond combining reducers, it applies these defaults:
- It adds the thunk middleware, so you can dispatch functions for async logic.
- In development, it adds a check that throws if state is mutated outside a reducer.
- In development, it adds a check that warns when state or actions contain values that cannot be serialized, such as class instances or functions.
- It connects the store to Redux DevTools.
Adding middleware
The middleware option takes a callback that receives getDefaultMiddleware. Call it and use .concat() to add to the defaults.
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
const logger = (storeApi) => (next) => (action) => {
console.log('dispatching', action.type)
return next(action)
}
export const store = configureStore({
reducer: { counter: counterReducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(logger),
})Common errors
- Replacing the defaults. Passing
middleware: [logger]directly removes the thunk middleware and the development checks. Use the callback form with.concat(). - Non-serializable values. Putting a
Date,Mapor function in state or in an action triggers a warning. Store a string or number, such as an ISO date or a timestamp, instead. - Mutating state outside reducers. The mutation check throws an error. Move the change into a reducer.
- Several stores. An app normally has one store. Create it once in its own module and import it where needed.
Exercise
You write configureStore({ reducer: { counter: counterSlice.reducer }, middleware: [logger] }). Async thunks stop working. Why, and how do you fix it?
Show answer
Passing an array to middleware replaces the defaults, which removes the thunk middleware. Use the callback form instead: middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger).
Exercise
A store is created with reducer: { counter: counterSlice.reducer }. What is the path to the counter's value in state?
Show answer
state.counter.value. The key in the reducer object (counter) becomes the top-level key.