new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Redux Toolkit · API · all subjects

combineslices

33 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

combineSlices function overview

combineSlices is a function that combines slices into a single reducer and enables injection of more reducers after initialisation.

combineSlices accepts slices and reducer map objects

combineSlices accepts a set of slices and/or reducer map objects as parameters. Slices are mounted at their reducerPath, and items from reducer map objects are mounted under their respective key.

combineSlices what counts as a slice

A slice for combineSlices is typically created with createSlice but can be any slice-like object with reducerPath and reducer properties. RTK Query API instances are compatible.

combineSlices reducer path collision behavior

If multiple slices or map objects have the same reducer path, the reducer provided later in the arguments overrides the previous one. However, typing will not account for this collision.

combineSlices return type interface

combineSlices returns a reducer function extending Reducer<DeclaredState, AnyAction, Partial<DeclaredState>> with attached methods: withLazyLoadedSlices(), inject(slice, config?), and selector object with selector(selectorFn, selectState?) and original(state) methods.

withLazyLoadedSlices method signature

withLazyLoadedSlices is a method on the combined reducer that accepts a generic type parameter LazyLoadedSlices and returns CombinedSliceReducer<InitialState, DeclaredState & Partial<LazyLoadedSlices>>. It allows you to declare slices that will be added to state later, which will be included in the final state type.

inject method signature and purpose

The inject method allows you to add a slice to your set of reducers after initialisation. It accepts a slice and an optional config parameter, and returns an updated version of the reducer with the slice included. This is mainly useful for lazy loading reducers.

inject adds reducer to map but doesn't dispatch action

The inject method adds the slice to the map of reducers in the original reducer but doesn't dispatch an action. This means the added reducer state will not show up in the store until the next action is dispatched.

inject reducer replacement default behavior

By default, replacing a reducer is not allowed. In development mode, a warning is logged to console if a new reducer instance is attempted to inject into a reducerPath that is already injected. No warning is logged if the same reducer instance is injected into the same place twice.

inject InjectConfig overrideExisting option

The inject method accepts an optional InjectConfig with overrideExisting boolean property. When overrideExisting is true, a reducer can be replaced with a new instance. This is useful for hot reload or removing a reducer by replacing it with a function that always returns null.

selector method behavior and purpose

The selector method wraps a selector function with a Proxy that ensures any currently injected reducers evaluate to their initial state if they are currently undefined in state. This allows you to work with possibly-optional state more conveniently in selectors.

selector method signature

The selector method is called as selector(selectorFn, selectState?) where selectorFn is a Selector function and selectState is an optional SelectFromRootState callback. It returns a WrappedSelector.

selector Proxy implementation detail pitfall

The Proxy retrieves a reducer's initial state by calling it with a randomly generated action type. Do not try to handle this as a special case inside your reducer.

selector nested combined reducer usage

When the combined reducer is nested further inside the store state, pass a selectState callback as the second argument to selector to extract the combined reducer state from the root state.

selector.original method

An original function is provided as a method on the selector function to retrieve the original state value provided to the Proxy. This is mainly useful for debugging and inspecting, as Proxy instances are hard to read in console output.

createSlice injectInto method

Slice instances returned by createSlice have an attached injectInto method that receives an injectable reducer from combineSlices and returns an injected version of that slice.

injectInto method configuration

The injectInto method accepts an optional configuration object that follows inject's options with an additional reducerPath field for injecting the slice under a path other than its current reducerPath property.

injected slice selectors behavior

The selectors from an injected slice instance behave like the selector method: if the slice state is undefined in the store state passed, the selector is called with the slice's initial state instead. Selectors also reflect changes in reducerPath if one was made during injection.

combineSlices basic usage example

Example showing basic combineSlices usage: import { combineSlices } from '@reduxjs/toolkit'; import { api } from './api'; import { userSlice } from './users'; export const rootReducer = combineSlices(api, userSlice); Then pass rootReducer to configureStore.

combineSlices with reducer map example

Example showing combineSlices usage with mixed slices and reducer map objects: const rootReducer = combineSlices(counterSlice, baseApi, { user: userSlice.reducer, auth: authSlice.reducer, }). This is equivalent to using combineReducers with slices mounted at their reducerPath and map items at their respective keys.

combineSlices lazy loading with declaration merging example

Example pattern for managing lazy loaded slices using declaration merging: Create an empty LazyLoadedSlices interface in slices/index.ts, call combineSlices(staticSlice).withLazyLoadedSlices<LazyLoadedSlices>(), then in lazySlice.ts extend the LazyLoadedSlices interface using declare module and inject the slice.

combineSlices inject usage example

Example of injecting a slice: const reducerWithUser = rootReducer.inject(userSlice). Or with configuration: const reducerWithUser = rootReducer.inject(userSlice, { overrideExisting: true }).

combineSlices selector wrapping example

Example showing selector wrapping: const wrappedSelectCounterValue = withCounter.selector((rootState) => rootState.counter.value). Returns 0 for empty state {}, and 2 for state { counter: { value: 2 } } due to Proxy initialization.

combineSlices selector with nested reducer example

Example of selector with nested combined reducer: const selectCounterValue = withCounter.selector((combinedState) => combinedState.counter.value, (rootState: RootState) => rootState.innerCombined). The second argument extracts the combined reducer from the root state.

combineSlices injectInto usage example

Example of using injectInto: const injectedCounterSlice = counterSlice.injectInto(rootReducer). Or with custom path: const aCounterSlice = counterSlice.injectInto(rootReducer, { reducerPath: 'aCounter' }).

combineSlices injected slice selectors example

Example showing injected slice selector behavior: injectedCounterSlice.selectors.selectValue({}) returns 0 (initial state), injectedCounterSlice.selectors.selectValue({ counter: { value: 2 } }) returns 2, and aCounterSlice.selectors.selectValue({ aCounter: { value: 2 } }) returns 2 (using the injected reducerPath).

combineSlices API for reducer injection and code-splitting

Redux Toolkit 2.0 includes a new combineSlices API designed for lazy-loading reducers at runtime. It accepts individual slices or an object of slices and calls combineReducers using each slice's name field as the state key. The returned reducer has an .inject() method to dynamically inject additional slices at runtime, and a .withLazyLoadedSlices() method to generate TypeScript types for reducers added later.

combineSlices basic usage example

Example of using combineSlices: const stringSlice = createSlice({ name: 'string', initialState: '', reducers: {} }) const numberSlice = createSlice({ name: 'number', initialState: 0, reducers: {} }) const booleanReducer = createReducer(false, () => {}) const combinedReducer = combineSlices( stringSlice, { num: numberSlice.reducer, boolean: booleanReducer }, ) expect(combinedReducer(undefined, dummyAction())).toEqual({ string: stringSlice.getInitialState(), num: numberSlice.getInitialState(), boolean: booleanReducer.getInitialState(), })

combineSlices reducer injection example

Example of using combineSlices with lazy loading: const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<WithSlice<typeof numberSlice>>() // state.number doesn't exist initially expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined) // Inject the slice const injectedReducer = combinedReducer.inject(numberSlice) // state.number now exists expect(injectedReducer(undefined, dummyAction()).number).toBe(numberSlice.getInitialState()) // Original reducer also changed expect(combinedReducer(undefined, dummyAction()).number).toBe(numberSlice.getInitialState())

injectInto method for lazy-loaded slices

Call injectInto(rootReducer) on a slice to inject it into a root reducer that was created with combineSlices().withLazyLoadedSlices(). This allows slices to be dynamically added to the store while maintaining type safety through the LazyLoadedSlices interface extension.

Slice injectInto method for lazy loaded reducers

Call slice.injectInto(rootReducer) on a slice to prepare it for dynamic injection. The returned injected slice has a selectSlice method to retrieve the slice state from the root state. This enables lazy loading of reducers while maintaining type safety.

combineSlices withLazyLoadedSlices pattern

Use combineSlices().withLazyLoadedSlices<LazyLoadedSlices>() to create a root reducer that supports dynamically injected slices. Define the LazyLoadedSlices interface to type the injected slices, and declare a module augmentation at the top level to enable type checking.

combineSlices combines multiple slices with lazy loading

combineSlices() combines multiple slices into a single reducer, and allows lazy loading of slices after initialisation.

Give your agent this brain