Initial reducer composition
Create a root reducer from feature slices and pass it to configureStore.
Redux Toolkit · Function
Combines Redux Toolkit slices and reducer maps into one reducer, mounting slices by reducerPath or map key. The returned reducer supports injecting additional slices after initialization.
combineSlices builds one reducer from slices and reducer-map entries. Each slice is mounted using its reducerPath, while map entries use their object keys; the returned reducer also exposes methods such as inject for adding slices after initialization.
combineSlices(...slices)| Name | Type | Description |
|---|---|---|
slices | SliceLike | ReducerMap | Array<SliceLike | ReducerMap> | Slices and/or reducer-map objects to combine; slices mount at reducerPath and map entries mount under their keys. |
A reducer function with attached methods, including inject for adding slices after initialization.
import { configureStore, createSlice, combineSlices } from '@reduxjs/toolkit'
const todos = createSlice({
name: 'todos',
initialState: [],
reducers: {
added: (state, action) => { state.push(action.payload) }
}
})
const rootReducer = combineSlices(todos)
const store = configureStore({ reducer: rootReducer })
store.dispatch(todos.actions.added('Learn Redux'))
console.log(store.getState().todos)Creates a slice, combines it into a root reducer, and passes that reducer to a configured store.
Create a root reducer from feature slices and pass it to configureStore.
Load a feature's reducer only when its code is needed.
Combine RTK Query API reducers with regular Redux slices.
combineSlices do?combineSlices accepts slices and reducer-map objects and returns one reducer. Slice state is mounted at each slice's reducerPath, while map entries use their corresponding keys.
Follow-up: How would you support code splitting? Call rootReducer.inject(lazySlice) after the initial reducer has been created, then use the returned reducer instance.
The returned reducer has attached methods, including inject. That method adds a slice after initialization and returns an updated version of the reducer containing it.
Follow-up: What must a slice provide to be compatible? It needs the slice-like shape expected by the API, including reducerPath and reducer.
Pass the reducer returned by combineSlices as the store's reducer, such as configureStore({ reducer: rootReducer }). The combined reducer can then manage the initial and injected slices.
Follow-up: Why use this instead of manually combining reducers? It combines slices while also supporting reducer injection for lazily loaded features.
configureStorecreateSlicecombineReducersinject