v2.15.0
This feature release gives each store its own RTK Query middleware runtime, makes initiate() promises resolve with their own request's result, adds several new options to RTK Query, improves listener middleware fork child capabilities, improves readability for several RTK type definitions, and fixes a variety of RTKQ bugs.
This release continues the work from our roadmap to Redux Toolkit 3.0. Several of the RTK Query changes here are bug fixes that change behavior in edge cases, so please read the "Behavior Changes" notes below.
RTK Query's middleware keeps a lot of state outside the Redux store in order to manage requests and cache lifetimes: subscriber counts, running requests, poll and cache collection timers, and cache lifecycle promises. That state used to live in closures shared by every store that used the same api object. That was fine for a single client-side store, but caused problems for SSR and tests, where many stores share one api.
Each store now gets its own consolidated internal runtime state, created by the API middleware. resetApiState now calls runtime.reset(), which clears every subscriber, timer and cache lifecycle for that store, aborts running requests, and clears pending tag invalidations. It no longer touches other stores.
Internally, each cache key now has one record that tracks its running request, timers and lifecycle, and all removals go through a single path. That made the initiate() fixes below possible.
The missing-middleware check now runs once per store, and looks for the store's runtime instead of dispatching an internal action. This check is stricter: an api whose middleware is missing now throws even if another api with the same reducerPath has its middleware in the store.
We had several long-standing reports (#5506, #4833, #5173, #5346) that the promise from initiate() could resolve with undefined, or with a different request's data. That happened when the cache entry was removed, reset, invalidated or replaced while the request was running, because the promise read the cache entry after the request finished instead of the request's own result.
We've done a thorough review of the promise resolution logic to analyze the current intended behavior, ran separate formal modeling of the derived behavior to help uncover gaps, updated the model to fill those gaps, and reworked that logic to fully comply with the improved expected behavior.
Each initiate() promise now resolves with its own request's result, captured as soon as that request's fulfilled or rejected action reaches the store.
Thanks to @kkatalz (#5474) and @rajanpanth (#5347): both PRs fixed part of this, and their tests are included.
These ship in 2.x as bug fixes, but code that depended on the old behavior will see a difference:
-
Removing a cache entry while its request runs now aborts that request. This covers
removeQueryResult, a lazy query'sreset(), cache collection, andresetApiState. Theinitiate()promise resolves withisError: trueand anAbortErrorwhose message is'removed'or'reset'. That meansunwrap()now rejects in this case, where it used to resolve with stale or missing data. The plain promise still never rejects. -
queryFulfilledinonQueryStartedrejects in the same case. If youronQueryStarteddoesawait queryFulfilledwithout atry/catch, you'll now get an unhandled rejection when the entry is removed mid-request. Wrap it:async onQueryStarted(arg, { queryFulfilled }) { try { const { data } = await queryFulfilled // ... } catch { // request failed, or the cache entry was removed while it ran } }
-
Invalidating an entry that has a running request (by tags, or a focus/reconnect refetch) now waits for that request to finish. The running request's promise gets its own result, and then the entry refetches if it has subscribers, or is removed if it doesn't.
-
A refetch while a request is running joins that request instead of starting another one.
initiate()also joins a runningupsertQueryData. -
A
pendingentry restored from persisted state, with no request actually running, now fetches again.
onCacheEntryAdded has a new getCacheEntryRemovedReason() function that returns 'reset' if the entry was removed by resetApiState, 'removed' for any other removal, or undefined while the entry is still in the cache. cacheEntryRemoved stays a Promise<void>, since many apps declare that type in their own handler types.
async onCacheEntryAdded(arg, { cacheEntryRemoved, getCacheEntryRemovedReason }) {
const connection = openConnection(arg)
await cacheEntryRemoved
if (getCacheEntryRemovedReason() !== 'reset') {
connection.unsubscribe()
}
connection.close()
}
We've had a request (#4757) to know why a query is fetching. For example, a queryFn might want to read from the primary database after a tag invalidation, instead of a replica that may be behind.
baseQuery / queryFn (via BaseQueryApi), fetchBaseQuery's prepareHeaders, onQueryStarted and onCacheEntryAdded now receive a startReason. The new QueryStartReason type is 'initial' | 'refetch' | 'invalidation' | 'poll' | 'focus' | 'reconnect' | 'upsert' | 'hydrate' | 'nextPage' | 'previousPage'.
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/api',
prepareHeaders: (headers, { startReason }) => {
if (startReason === 'invalidation') {
headers.set('x-read-from-primary', 'true')
}
return headers
},
}),
endpoints: () => ({}),
})
A few details: 'initial' vs 'refetch' depends on whether the entry already has data. Mutations get startReason: undefined. 'hydrate' is reserved for upcoming hydration work and isn't set yet. We may add additional values in the future if needed.
pollingInterval can now be a function that receives the current cache entry and returns an interval in ms (#2639). This covers "poll while a job is running, stop when it's done" without a second hook:
useGetJobQuery(id, {
pollingInterval: ({ data }) => (data?.status === 'running' ? 1000 : 0),
})
It works in all the query hooks, initiate() and updateSubscriptionOptions. The function runs once per cache key when the next poll is scheduled after a request settles. When several subscribers poll the same key, the lowest result wins, the same as numeric intervals. Returning 0, a negative number or a non-number means "don't poll", and polling resumes if a later request makes the function return an interval again. An inline function in a hook doesn't dispatch updateSubscriptionOptions on every render.
Related changes:
- A negative numeric
pollingIntervalnow means "no polling". Before, it re-polled immediately in a loop. 'payload.options.pollingInterval'is a new default entry in the serializability check'signoredActionPaths. If you pass your ownignoredActionPaths, you'll need to add it.SubscriptionOptions['pollingInterval']is nownumber | ((entry) => number), so code that reads it as anumberneeds a type check. There's a new exportedPollingIntervaltype.
api.endpoints.x.getRunningQuery(arg) is a typed thunk for query and infinite query endpoints. Dispatching it returns the promise of the running request for that cache entry, or undefined. It's the same promise the initiate() call that started the request returned, and awaiting it doesn't add a subscription. It's the typed per-endpoint form of api.util.getRunningQueryThunk.
Query initiate() has a new retainFor option, in seconds. After the last subscriber leaves, the entry is kept for Math.max(keepUnusedDataFor, retainFor) seconds. This is useful for prefetching or subscribe: false requests whose data will be read soon:
dispatch(api.endpoints.getPost.initiate(id, { subscribe: false, retainFor: 60 }))
// later
const running = dispatch(api.endpoints.getPost.getRunningQuery(id))
if (running) {
await running
}
There's also a new dev-only warning when an infinite query page fetch joins a running fetch in the other direction, like calling fetchNextPage() while fetchPreviousPage() is running. The second call still joins and doesn't fetch its own page, same as before.
The React hooks used to dispatch an internal internal_getRTKQSubscriptions action to check subscription status, and some libraries copied that pattern. We've added real APIs for it:
api.util.getMiddlewareState()is a thunk that returns read-only access to what the middleware tracks for that store (currentlygetSubscriptionCount(queryCacheKey)), orundefinedif the middleware isn't added (#5501).- Query
initiate()results have anisSubscribed()method.
The hooks use isSubscribed() now, and don't dispatch anything to check subscriptions. The internal_getRTKQSubscriptions action is deprecated. It still works in 2.x, but logs a one-time dev warning and will be removed in 3.0. If you maintain a library that dispatches it (such as a port of the RTKQ hooks to another framework), switch to getMiddlewareState() and isSubscribed().
The hooks also no longer run their own missing-middleware check. A hook with skip: true on a store without the API middleware no longer throws. A non-skipped hook still throws, from the check in initiate().
ForkedTaskAPI now has getState, dispatch and fork, so a forked task can read state, dispatch actions and start its own child tasks (#3314). Nested forks are cancelled when the task that forked them ends or is cancelled. A nested fork with autoJoin: true makes its parent wait for it before completing.
listenerMiddleware.startListening({
actionCreator: startSync,
effect: async (action, listenerApi) => {
listenerApi.fork(async (forkApi) => {
const { userId } = forkApi.getState().auth
forkApi.fork(
async (childApi) => {
childApi.dispatch(syncStarted(userId))
},
{ autoJoin: true },
)
})
},
})
ForkedTaskAPI and the task executor types have optional State and DispatchType generics, which flow through startListening, addListener and their withTypes() versions. Like the listener's own getState and dispatch, these aren't guarded after the task finishes. With some internal cleanup in the same PR, the listener middleware is slightly smaller even with the new API.
Hovering over RTK and RTKQ types in an editor often showed a wall of text that the editor cut off at 500 characters, along with odd names like Slice$1 and IsAny. We've added named types so hovers show a name instead of the full structure: FetchBaseQueryFn, ApiUtil, ListenerMiddlewareDispatch, AsyncThunkPromise and ReactApiModules. The query, mutation and infinite query selector result types were rewritten so TypeScript keeps their names. Some hover lengths, before and after:
| Hover | Before | After |
|---|---|---|
useMutation tuple |
2508 | 386 |
endpoints.getPost.select(...) |
2399 | 602 |
api.util |
16102 | 471 |
dispatch(thunk(...)) |
552 | 71 |
These are type-only changes. Please let us know if the selector result rewrite causes problems in code that's generic over endpoint definitions.
When several subscribers share a query, RTKQ combines their options. Some of those rules skipped refetches that a subscriber asked for (#5583). Each subscriber's options are now resolved before they're combined:
refetchOnMountOrArgChange: 0andforceRefetch: 0now always refetch. Before,0disabled the option.refetchOnFocusandrefetchOnReconnectrefetch a shared query if any subscriber's own or inherited setting istrue. One subscriber'sfalseno longer turns it off for the others.- Polling skips while unfocused only if every polling subscriber sets
skipPollingIfUnfocused. Non-polling subscribers don't affect this.
Thanks to @duckieeeduck for this fix!
An endpoint's maxRetries now caps retries even when the api-level retry() has a retryCondition. The retryCondition still decides which errors retry (thanks @luantaraschi!).
retry.fail() called inside a backoff function no longer nests the error inside { error, meta } (thanks @dfedoryshchev!).
fetchBaseQuery's timeout now works when the request passes its own signal (thanks @wozhenbang2004!). Query parameters are now added before a URL #fragment instead of after it (thanks @henricop!). FetchArgs.headers now accepts number and boolean values, which are converted to strings. They already worked at runtime (thanks @emersion!).
The entity adapter keeps the ids order when an update changes an entity's id (thanks @b84330808!).
Wrapping createSlice in a generic helper now keeps the prepare callback's parameter types (thanks @kkatalz!).
We've documented getCacheEntryRemovedReason, startReason, getRunningQuery, retainFor, getMiddlewareState, isSubscribed, function pollingInterval and nested forks, and fixed several smaller doc and JSDoc errors.
- Refactor RTKQ middleware state into a per-store runtime by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5569
- Give each store its own RTKQ middleware runtime, with
reset()by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5570 - Add
getState,dispatch, andforktoForkedTaskAPIby @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5572 - Fix public type names shown in editor hovers (
Slice$1,IsAny) by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5575 - Add
api.util.getMiddlewareState()andisSubscribed()on queryinitiate()results by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5579 - Track each cache key's request, timers and lifecycle through record transitions by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5586
- Resolve
initiate()promises with their own request result, and remove entries through one path by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5587 - Settle and abort every running request for a key when its entry is removed by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5589
- Add named public types so editor hovers stay readable by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5576
- Fix endpoint maxRetries being ignored with a retry() retryCondition by @luantaraschi in https://github.com/reduxjs/redux-toolkit/pull/5590
- Add
startReasontoBaseQueryApiand query lifecycle APIs by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5601 - Add
endpoint.getRunningQueryandinitiateretainForoption by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5602 - Allow
pollingIntervalto be a function of the cache entry by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5604 - fix(toolkit): keep
prepareparameter types when wrappingcreateSliceby @kkatalz in https://github.com/reduxjs/redux-toolkit/pull/5591 - fix(entityAdapter): keep ids order when an update changes an entity id by @b84330808 in https://github.com/reduxjs/redux-toolkit/pull/5573
- fix(toolkit):
fetchBaseQuerytimeouts when a request provides a signal by @wozhenbang2004 in https://github.com/reduxjs/redux-toolkit/pull/5595 - Fix refetch defaults and shared polling preferences by @duckieeeduck in https://github.com/reduxjs/redux-toolkit/pull/5593
- fix(toolkit):
retry.fail()in abackofffunction nesting the error in{ error, meta }by @dfedoryshchev in https://github.com/reduxjs/redux-toolkit/pull/5612 - fix(query): append query parameters before URL fragments by @henricop in https://github.com/reduxjs/redux-toolkit/pull/5598
- fix(query): allow boolean/number in headers by @emersion in https://github.com/reduxjs/redux-toolkit/pull/5621
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.14.0...v2.15.0
v2.14.0
This feature release speeds up the dispatch path and RTK Query's Api type checking, shrinks createSlice in esbuild bundles, adds RTK-owned Draft and Patch types so emitted declarations no longer reference Immer, adds removeMany({ where }) and selectByIds to the entity adapter, adds RTK Query cache entry selectors and a DevTools action sanitizer, and fixes a very long list of RTK Query lifecycle, polling, upsert, timer, hook and fetchBaseQuery bugs.
Note that we just announced our roadmap to Redux Toolkit 3.0, which includes both a large set of planned 2.x features and improvements, and planned 3.0 breaking changes. The fixes and updates in this release help pave the way for all of those efforts. We'd also appreciate feedback on the linked RTK Query usage patterns and 3.0 planned breaking changes discussion threads.
Every dispatched action runs through every reducer and middleware, so small costs on that path add up. We added a benchmark harness for the dispatch path and used it to find several places where RTK did work for actions it didn't care about.
createAction(...).match now compares action.type before calling isAction, so a non-matching action costs a property read. createReducer no longer allocates arrays on every dispatch to collect case and matcher reducers. Since createSlice builds its reducer with createReducer, every slice reducer gets this improvement.
The listener middleware used to copy its listener list and call every predicate for every action. It now keeps a snapshot that is rebuilt only when listeners are added or removed, and that snapshot knows which action types have type or actionCreator listeners. If an action's type isn't in that set and there are no matcher or predicate listeners, the middleware skips the loop entirely.
The RTK Query root reducer now returns the existing state for actions that none of its slices handle, instead of running all five slice reducers. It also skips rewriting a query's provided tags when the new tags are the same as the stored ones, so re-fetching a query that returns the same tags no longer creates new provided state.
Some numbers from the PR benchmarks (Node 26, ops/sec unless noted):
| Scenario | Before | After |
|---|---|---|
| Listener middleware, 200 listeners, unrelated action | 108K | 5.34M |
Listener middleware, 200 actionCreator listeners, matching action |
100K | 612K |
createSlice, 20 slices, unrelated action |
320K | 394K |
| RTKQ store, unrelated action | 352K | 468K |
| RTKQ re-dispatch of a fulfilled query with unchanged tags, 1000 entries (ms per dispatch) | 2.50 | 0.55 |
The listener middleware numbers are the biggest change, because the old cost grew with the number of listeners. Apps with a handful of listeners will see much smaller gains.
The RTK Query middleware also does less work keeping the store's subscriptions state in sync (#5499). It used to JSON-copy the whole subscriptions object and diff it with Immer every 500ms while subscriptions were changing. It now records which cache keys changed and writes one patch per key. Keys that didn't change keep their object references, so the Redux DevTools no longer receive a full copy of subscriptions on every sync. Polls, refetch() calls and tag invalidation refetches don't add subscribers, so they no longer schedule a sync at all. The visible difference: a cache key that only ever had subscribe: false requests no longer shows up as an empty {} in subscriptions.
createSlice references asyncThunkCreator so that create.asyncThunk works in the reducers callback. esbuild couldn't tell that the asyncThunkCreator object was free of side effects, so it always bundled createAsyncThunk along with createSlice. webpack already dropped it. We've marked it as pure, and an esbuild bundle that imports only createSlice is now about 1 kB smaller (brotli).
The Api type combines every registered module (core, React hooks, and any third-party modules) by running UnionToIntersection over the module names. TanStack Table hit the same cost with the same design, and found that writing out the known intersection and adding variance annotations helped a lot.
We've done the same thing here: Api uses the core module type directly, and ApiModules has in out variance annotations. On a test app with one ~50-endpoint createApi, type instantiations dropped 22% and check time dropped about 25% on TS 6, and about 18% on the TS 7 native preview. Third-party modules like ngrx-rtk-query saw 7-8% fewer instantiations. There are no runtime changes.
RTK used to re-export Immer's Draft type, and used Immer's types in signatures like CaseReducer and PatchCollection. That meant the .d.ts files TypeScript generated for your slices referenced immer. With a package manager layout where immer isn't hoisted, those declarations failed to build with TS2883 (#5516). Re-exporting doesn't fix that, so RTK now declares its own Draft, WritableDraft and Patch types with the same shapes as Immer's. Emitted declarations now point at @reduxjs/toolkit instead. Our type tests check that RTK's Draft and Immer's Draft stay interchangeable, so code that mixes castDraft or current with RTK's types keeps working. We also bumped the immer dependency to ^11.2.9.
There are a few other type additions in this release:
ApiRootStatereplaces RTK Query'sRootStatetype, which is now deprecated.RootStatewill be removed in 3.0.TypedAddListenerActionandTypedRemoveListenerActiondescribe the actions thataddListenerandremoveListeneractually dispatch. The default payload type ofTypedAddListenerandTypedRemoveListeneris now the listener options object, soaddListener.match(action)no longer claimsaction.payloadhas fields likeidandunsubscribethat don't exist at runtime.dispatch(removeListener(...))is typed as returningbooleananddispatch(clearAllListeners())as returningvoid, matching the runtime.UseQueryStateDefaultResultandUseInfiniteQueryStateDefaultResultare exported from@reduxjs/toolkit/query/react, for wrapping hooks with a genericselectFromResult.
We've had requests for a way to list everything in the cache for an endpoint (#2995). api.util.selectEntriesForEndpoint(state, endpointName) returns all cache entries for one query or infinite query endpoint, and api.util.selectAllQueryEntries(state) returns them for every endpoint. Each item has the entry's fields plus its queryCacheKey, and is typed for its endpoint. Both selectors are memoized. There's also a new exported QueryCacheEntry<Definition> type.
const postEntries = api.util.selectEntriesForEndpoint(state, 'getPost')
const loadedPostIds = postEntries
.filter((entry) => entry.status === 'fulfilled')
.map((entry) => entry.originalArgs)
All RTK Query requests use the same few action types, so the Redux DevTools show a long list of api/executeQuery/fulfilled actions, and you have to open each one to see which endpoint it was for. The new createApiActionSanitizer(api) returns a function for the DevTools actionSanitizer option that renames those actions for display, like api/executeQuery/fulfilled (getPosts). The dispatched actions aren't modified.
import { configureStore } from '@reduxjs/toolkit'
import { createApiActionSanitizer } from '@reduxjs/toolkit/query'
import { api } from './api'
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
devTools: {
actionSanitizer: createApiActionSanitizer(api),
},
})
See the createApiActionSanitizer docs for combining sanitizers for multiple APIs.
adapter.removeMany now accepts a { where } object, and removes every entity whose fields match all the given values (#5524):
postsAdapter.removeMany(state, { where: { authorId: 5 } })
The match object is typed as Partial<T>, and values are compared with ===. A where object with no keys removes nothing, so a filter built at runtime that ends up empty can't clear the collection by accident. Use removeAll for that. There's also a new exported RemoveManyFilter<T> type.
getSelectors() now includes selectByIds(state, ids), which returns the entities for the given ids in the order of ids, skipping ids that don't exist.
removeMany is also faster. It used to filter the Immer draft of the ids array, which reads every element through the draft proxy. It now filters a plain copy against a Set of removed ids.
Lifecycles: cacheDataLoaded now only resolves for a response from a request that started while that lifecycle was waiting. A late response from before a removeQueryResult no longer resolves the next lifecycle on the same key with discarded data. Re-triggering a mutation with the same fixedCacheKey now ends the previous onCacheEntryAdded lifecycle, so its cacheEntryRemoved cleanup runs instead of leaking. If that earlier trigger is still in flight, its cacheDataLoaded now rejects instead of never settling. Thanks to @hamarshehmhmd for the analysis in #5539. getCacheEntry() in a mutation's onQueryStarted now finds the entry for fixedCacheKey mutations instead of always returning uninitialized.
Synchronous throws from onQueryStarted and onCacheEntryAdded are now caught and logged with console.error. Before, a sync throw in onQueryStarted escaped the pending dispatch and failed the request without ever calling queryFn. We also added a dev warning when updateCachedData is called before the entry has any data, since that call does nothing.
Polling: Polling now stops after the last unsubscribe even if the subscription cleanup hasn't run yet (thanks to @LeulTew for the original fix in #5444). A due poll re-reads skipPollingIfUnfocused instead of using the value from when the timer was set, and skips the poll if a request for that entry is already pending. pollingInterval values above 2^31-1 ms are now clamped with a dev warning, since larger values overflow setTimeout and fire after 1ms. Removing a cache entry with removeQueryResult now stops its poll timer right away, and switching a subscriber to a slower pollingInterval now reschedules the pending poll instead of letting the old, faster one fire once more. We also fixed a stale internal poll record that could block updatePollingInterval, and fetchBaseQuery now clears its timeout timer when the request finishes.
Upserts: A failed upsertQueryData over an existing entry (for example, from a responseSchema validation error) no longer leaves that entry stuck in pending. upsertQueryEntries now skips bad entries one at a time instead of failing the whole batch: unknown or mutation endpoint names and throwing providesTags callbacks are skipped, with dev warnings.
Timers and multiple stores: resetApiState now clears the subscription sync timer and the state for delayed tag invalidation, so work scheduled before the reset can't fire afterward. A keepUnusedDataFor removal timer is now cleared when the key gets a new subscriber or is removed with removeQueryResult, so an old timer can't remove a newer entry for the same key. Repeated initiate(arg, { subscribe: false }) calls that hit the cache no longer push back the keepUnusedDataFor removal, which could keep unused data around indefinitely (#4480, thanks @veksa!). setupListeners now works with more than one store. Before, only the first store got focus and online events.
Hooks: A query that failed before it ever got data now reports isLoading: true when it refetches, instead of having isLoading, isError and data all falsy while the request is pending (#4449, thanks @AnimeshPandey!). This undoes a change from 2.2.4 (#4364) that kept isLoading false when a second hook subscribed to an errored entry. If a parent renders null while isLoading is true and a child mounts the same query, the parent now unmounts the child on each refetch, and the two can loop. Render the child based on data or isError instead. Query args containing NaN no longer cause an endless refetch loop when the query errors. This was a regression from 2.9.0, where arg comparison treated NaN as never equal to itself (#5338, thanks @aagostino31!). fetchNextPage() and fetchPreviousPage() no longer send a request when the infinite query hook's arg is skipToken, and initiate(skipToken) no longer sends a request for any query or infinite query endpoint (#5028, thanks @haigou-web!).
fetchBaseQuery: A null body no longer throws Cannot read properties of null before the request is sent (thanks @dfedoryshchev!). An explicit content-type header is now kept for ArrayBuffer, typed array and Blob bodies, which broke presigned S3 and GCS uploads. It's still removed for FormData and for a JSON content type on a non-JSON body, and that JSON content type check is now case-insensitive (thanks @tad-bit-better!). A custom responseHandler that throws or rejects with a falsy value like undefined now produces a PARSING_ERROR, instead of being treated as a successful response (#5480, thanks @JunaidAhamed-7777!). A timeout that fires while the response body is being read is now reported as TIMEOUT_ERROR instead of PARSING_ERROR (thanks @Gurmehar-git!).
Other RTKQ fixes: An overlapping refetch now stays registered as the running query, so later calls join it and aborting it works (thanks @tedy69!). Apps with many createApi middlewares could hit a "Maximum call stack size exceeded" error when the middlewares registered themselves on the first query. Registration no longer restarts dispatch from the start of the middleware chain (thanks @PabloJoan!). api.enhanceEndpoints({ endpoints }) now logs an error in development when it names an endpoint that doesn't exist, which usually means a typo.
RTK Query thunk actions now include startedTimeStamp and a per-store seq counter in the fulfilled and rejected-with-value meta, matching the request's pending action, so you can tell which request a response belongs to and in what order requests started. Rejections for aborted requests and unhandled errors don't include these fields yet.
The listener middleware's take(), condition() and delay() no longer leave their timers running after the listener is cancelled or the action arrives first.
The autoBatchEnhancer raf fallback no longer throws a cancelAnimationFrame ReferenceError in test environments that delete window globals during teardown (thanks @msutkowski!).
RTK Query hooks now log a dev warning when they render with a different store than the one they first subscribed to. If you swap the store passed to <Provider>, give the Provider a key that changes with the store so the tree remounts.
The serializability check middleware now reports a circular reference in state or actions as a non-serializable value, instead of overflowing the stack (thanks @OskarEichler!).
@types/react is now declared as an optional peer dependency. RTK's React entry points import React types, and with pnpm's isolated linker or a global virtual store, TypeScript couldn't find them and those types became any (thanks @unrevised6419!).
- fix(toolkit):
cancelAnimationFrameReferenceError in the autoBatch raf fallback by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/5462 - Add a dispatch-path benchmark harness by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5537
- Fix listener
take/delaytimer leak and documentisAnyOfmatcher inference by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5538 - fix(query): keep overlapping refetches in the running query registry by @tedy69 in https://github.com/reduxjs/redux-toolkit/pull/5478
- Fix RTK Query polling timer bugs by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5541
- Speed up
removeManyin the entity adapter by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5546 - Fix stuck
pendingafter failedupsertQueryData, and skip badupsertQueryEntriesentries by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5542 - Fix stale
cacheDataLoaded,fixedCacheKey,getCacheEntry, and sync throws in RTKQ lifecycles by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5543 - Fix RTKQ middleware timer cleanup and
setupListenerswith multiple stores by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5545 - Speed up RTKQ
Apitype checking by writing out the core module by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5547 - Speed up the dispatch path in createAction, createReducer and listener middleware by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5553
- Skip RTKQ reducer work for unhandled actions and unchanged provided tags by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5552
- Add removeMany({ where }) and selectByIds to entity adapter by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5550
- Add startedTimeStamp and per-store seq to all RTKQ thunk meta by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5549
- Prevent registration of query middleware to restart dispatch from the beginning by @PabloJoan in https://github.com/reduxjs/redux-toolkit/pull/5281
- End the previous cache lifecycle when a fixedCacheKey mutation is re-triggered by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5554
- Document keying the Provider when swapping stores, and warn in dev by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5557
- Add enhanceEndpoints dev warning, query entry selectors, and createApiActionSanitizer by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5555
- Record RTKQ subscription sync patches directly and stop re-arming on non-subscribing requests by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5559
- Let esbuild tree-shake createAsyncThunk out of createSlice by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5561
- Add RTK-owned Draft/Patch types, ApiRootState, listener action types, and hook result types by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5560
- Stop RTKQ polls when the cache entry is removed, and reschedule for slower intervals by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5564
- fix(toolkit): don't treat a
nullbody as jsonifiable infetchBaseQueryby @dfedoryshchev in https://github.com/reduxjs/redux-toolkit/pull/5450 - Report circular serializable values without overflowing by @OskarEichler in https://github.com/reduxjs/redux-toolkit/pull/5421
- fix(query): don't reset
keepUnusedDataForon condition-skipped queries by @veksa in https://github.com/reduxjs/redux-toolkit/pull/5343 - fix(toolkit): declare @types/react as an optional peer dependency by @unrevised6419 in https://github.com/reduxjs/redux-toolkit/pull/5448
- Keep explicit content-type for binary bodies in
fetchBaseQueryby @tad-bit-better in https://github.com/reduxjs/redux-toolkit/pull/5479 - fix(toolkit): preserve falsy response handler errors by @JunaidAhamed-7777 in https://github.com/reduxjs/redux-toolkit/pull/5481
- fix(toolkit): report response body timeouts as
TIMEOUT_ERRORby @Gurmehar-git in https://github.com/reduxjs/redux-toolkit/pull/5482 - fix(toolkit): prevent infinite refetch loop when query args contain
NaNby @aagostino31 in https://github.com/reduxjs/redux-toolkit/pull/5339 - Fix
isLoadingstayingfalsewhen refetching after an error with no data by @AnimeshPandey in https://github.com/reduxjs/redux-toolkit/pull/5470 - fix(toolkit): respect
skipTokenin infinite query triggers by @haigou-web in https://github.com/reduxjs/redux-toolkit/pull/5464
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.13.0...v2.14.0
v2.13.0
This feature release updates our build tooling to TSDown and PNPM, adds official TypeScript 7 support, and includes a long list of bugfixes across RTK Query, createAsyncThunk, createEntityAdapter, and combineSlices.
We've fully modernizing modernized our build tooling across all of the Redux repos. That included switching from Yarn to PNPM, ESLint to Oxlint, Prettier to Oxfmt, and TSUp to TSDown.
The part that matters for users is that we now build the package with TSDown instead of tsup. The package layout, exports definitions, and exported APIs are all unchanged from 2.12. We've checked the new build with attw, and verified that CJS and ESM entry points load in both dev and prod builds, and that the legacy-esm artifacts still target ES2017. The contents of the bundles do look a bit different (smaller CJS artifacts, slightly different helper output in the legacy-esm files). If you see any behavior differences that look build-related, please file an issue!
This is also our first release published via the updated PNPM-based workflow, still using NPM Trusted Publishing. We've also added pkg.pr.new previews for every commit, so you can try out a PR build before it's released.
We've shipped a new combined Redux libraries docs site! The core docs site at https://redux.js.org now contains the docs for all of our libraries: Redux core and usage guides, Redux Toolkit, React Redux, and Reselect. The prior standalone docs sites for RTK, R-R, and Reselect now redirect to their respective sections of the combined docs. We've also done a major cleanup pass on the docs, deduplicating pages that had similarities (like the Next.js or RTK2 migration pages that lived in both the core and RTK docs), and updating outdated content (modernizing example code snippets, deleting dead links, and making RTK and hooks the default patterns shown). The RTK content now lives at https://redux.js.org/toolkit/ .
TS 7.0 (the native Go port) is now out! We fixed the remaining type errors in RTK when checked by TS 7.0 and 7.1, and TS 7.0 is now part of our CI test matrix.
Per our TS support policy of matching DefinitelyTyped's support window, we've also updated our support matrix to TS 5.6+. As always, RTK may still work with earlier versions, but we no longer test against them.
useQueryState (and thus useQuery) was passing a new inline selector to useSelector on every render, and also reading the store directly during render. The selector is now memoized, and the direct store read is gone. This also fixes a bug where isSuccess could flip from false to true on an unrelated re-render while a query was refetching after an error. isSuccess now correctly stays false in that case.
data now reflects cache updates made via updateQueryData while a refetch is in flight, instead of showing the previous result.
Polling now reads the current cache state when each poll fires, rather than the state at the time the poll was scheduled. This means skipPollingIfUnfocused respects focus loss that happens after scheduling, and polls stop if their cache entry was removed.
We fixed a race where a duplicate query request rejected by the thunk condition could cause queued tag invalidations to run too early and be lost, leaving stale data in the cache.
Tags with falsy ids like 0 now invalidate and clean up correctly.
Lazy query hooks now re-subscribe correctly when effects restart while the hook state is preserved, such as with Fast Refresh or <Activity>.
Infinite queries no longer trigger onQueryStarted when fetching past the end of the list, and the infinite query hook result type now includes the page error flags.
fetchBaseQuery only treats a URL as absolute if it starts with a scheme.
We also fixed an error when rehydrating state for an endpoint name that has no definition.
createAsyncThunk no longer swallows aborts that happen before the pending action is dispatched, and now correctly sets rejectedWithValue when rejectWithValue is called with a falsy payload.
createEntityAdapter's setAll now keeps the last item when given duplicate IDs, matching setMany. The sorted adapter's updateMany now merges multiple updates for the same ID before applying them.
combineSlices now keeps its internal state proxy cache per instance, so multiple combined reducers no longer interfere with each other.
The immutability check middleware now handles circular references in state.
The dynamic middleware now caches its composed middleware chains when the list of middleware hasn't changed.
- Additional publishing hardening by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5297
- ci: fix Playwright e2e tests in publish-ci examples by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/5310
- ci: publish preview packages on every commit via
pkg.pr.newby @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/5256 - feat(codegen): migrate to oazapfts v7 by @Suto-Michimasa in https://github.com/reduxjs/redux-toolkit/pull/5228
- fix(combineSlices): scope stateProxyMap per instance to prevent cross-instance proxy collisions by @JSap0914 in https://github.com/reduxjs/redux-toolkit/pull/5319
- fix(entityAdapter): pre-merge same-ID updates in sorted adapter's updateMany by @JSap0914 in https://github.com/reduxjs/redux-toolkit/pull/5323
- fix(
entityAdapter):setAllwith duplicate IDs keeps last occurrence (consistent withsetMany) by @JSap0914 in https://github.com/reduxjs/redux-toolkit/pull/5321 - fix(query): reflect cache updates in hook data by @jtiret in https://github.com/reduxjs/redux-toolkit/pull/5327
- fix: don't swallow
createAsyncThunkaborts that happen before pending by @chatman-media in https://github.com/reduxjs/redux-toolkit/pull/5314 - Simplify
useRef<T | undefined>(undefined)usages in RTK Query hooks by @DucMinhNe in https://github.com/reduxjs/redux-toolkit/pull/5315 - fix(query): prevent
onQueryStartedfrom triggering at end-of-list by @joseph0926 in https://github.com/reduxjs/redux-toolkit/pull/5182 - fix(types): fix tsgo (TS 7.0) type errors and re-enable the native-preview CI job by @veksa in https://github.com/reduxjs/redux-toolkit/pull/5344
- ci: bump GitHub Actions to their latest versions by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/5358
- chore(toolkit): remove redundant and unused type declarations by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/5356
- Modernize CI examples by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5363
- fix(rtk-query): only treat a url as absolute when it starts with a scheme by @MahinAnowar in https://github.com/reduxjs/redux-toolkit/pull/5428
- Modern Tooling, Part 1: Oxlint by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5384
- Modern Tooling, Part 2: Oxfmt by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5385
- Modern Tooling, Part 3: TSDown and TS6 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5386
- Modern Tooling, Part 4: Vitest type assertions by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5387
- Modern Tooling, Part 5: PNPM by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5388
- Modern Tooling, Part 6: TS7 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5389
- Modern Tooling, Part 7: vendor
remark-typescript-toolsand update to TS7 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5390 - Modern Tooling, Part 8: Vitest 5 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5436
- Remove redundant RTK Query example projects by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5443
- Type the reducer builder implementation explicitly for TS 7.1 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5446
- fix(toolkit): flag
rejectedWithValuefor falsyrejectWithValuepayloads by @dfedoryshchev in https://github.com/reduxjs/redux-toolkit/pull/5395 - Cache unchanged dynamic middleware chains by @OskarEichler in https://github.com/reduxjs/redux-toolkit/pull/5415
- Preserve delayed invalidations after duplicate query rejection by @OskarEichler in https://github.com/reduxjs/redux-toolkit/pull/5406
- Read current query state when scheduled polls fire by @OskarEichler in https://github.com/reduxjs/redux-toolkit/pull/5412
- fix(toolkit): prevent undefined endpoint reference by @adamaveray in https://github.com/reduxjs/redux-toolkit/pull/5377
- fix(toolkit): tag with a falsy id invalidation and cleanup by @petr-kratochvil in https://github.com/reduxjs/redux-toolkit/pull/5398
- fix(rtk-query): add infinite query page error flags to hook result type by @mvpowers in https://github.com/reduxjs/redux-toolkit/pull/5441
- Reinstate lazy queries after preserved effects restart by @OskarEichler in https://github.com/reduxjs/redux-toolkit/pull/5424
- fix(toolkit): handle circular references in
immutableStateInvariantMiddlewareby @hamed-bavar in https://github.com/reduxjs/redux-toolkit/pull/5433 - Fix TS7 errors and update TS matrix by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5455
- Fix unstable selector reference inside of
useQueryStateandisSuccessduring refetch-after-error by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5456
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.12.0...v2.13.0
v2.12.0
This feature release adds RTK usage skills files (via TanStack Intent) exports the RTK Query hook options types for reusability, fixes issues with infinite query status flags and batching handling, and makes some small TS improvements.
We've generated agent skill files that are now included in the RTK package itself in a skills folder. They cover using and migrating to modern RTK, client and server state management, and handling side effects. You can point your agent at these skills yourself, or use TanStack Intent to pick them up.
The types for our RTK Query hook options are now exported, which lets you stop using Parameters to extract those types for use in your own code.
The types for listener middleware matchers were tweaked to allow interface-based type guards, not just type-based definitions.
The internal IgnorePaths type was renamed to IgnoredPaths for consistency.
We now use the built-in NoInfer util that comes with TS 5.4+.
We fixed handling of the isSuccess status flag when switching infinite query cache entries. This should prevent accidental UI flashes that were occurring due to this flag accidentally flipping.
We've added a 100ms timeout fallback to the autoBatch enhancer's requestAnimationFrame timer. We had several reports that rAF didn't work correctly when used in background tabs / opened windows, and that RTK never updated the UI. This should ensure that the updates flush correctly.
- Export hook options types for RTK Query hooks by @veeceey in https://github.com/reduxjs/redux-toolkit/pull/5218
- Add TanStack Intent skills for Redux Toolkit by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/5249
- Keep isSuccess: true when switching infinite query cache entries by @riqts in https://github.com/reduxjs/redux-toolkit/pull/5268
- fix: allow interface-based type guards as listener matcher by @riqts in https://github.com/reduxjs/redux-toolkit/pull/5269
- fix: add setTimeout fallback to raf autoBatch strategy for background tabs by @riqts in https://github.com/reduxjs/redux-toolkit/pull/5273
- chore(toolkit): rename
IgnorePathstype toIgnoredPathsby @Ri5ha6h in https://github.com/reduxjs/redux-toolkit/pull/5284 - feat(toolkit)!: switch to native
NoInferutility type by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/5289
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.11.2...v2.12.0
v2.11.2
This bugfix release updates the AbortSignal handling to fall back if DOMException isn't available (such as RN environments), and updates the TypedUseInfiniteQueryHookResult type to correctly include fetchNextPage/fetchPreviousPage fields.
The AbortSignal changes in 2.11.1 used DOMException in a couple places to match the expected behavior of AbortSignal, but turns out that's not available in environments like React Native. We've updated the logic to fall back to a plain Error if DOMException isn't available.
The TypedUseInfiniteQueryHookResult type wasn't correctly including the fetchNextPage/fetchPreviousPage fields, and now it does.
- fix: use a normal Error when DOMException isn't available by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/5161
- Include page functions in
TypedUseInfiniteQueryHookResultby @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5165
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.11.1...v2.11.2
v2.11.1
This bugfix release fixes an issue with our internal AbortSignal handling that was reported as causing an error in a rare reset situation. We've also restructured our publishing process to use NPM Trusted Publishing, and updated our TS support matrix to only support TS 5.4+.
We've previously done most of our releases semi-manually locally, with various release process CLI tools. With the changes to NPM publishing security and the recent wave of NPM attacks, we've updated our publishing process to solely use NPM Trusted Publishing via workflows. We've also done a hardening pass on our own CI setup.
We had done a couple releases via CI workflows previously, and later semi-manual releases caused PNPM to warn that RTK was no longer trusted. This release should be trusted and will resolve that issue.
Thanks to the e18e folks and their excellent guide at https://e18e.dev/docs/publishing for making this process easier!
We've previously mentioned rolling changes to our TS support matrix in release notes, but didn't officially document our support policy. We've added a description of the support policy (last 2 years of TS releases, matching DefinitelyTyped) and the current oldest TS version we support in the docs:
- https://redux-toolkit.js.org/introduction/getting-started#typescript
- https://redux-toolkit.js.org/usage/usage-with-typescript#introduction
As of today, we've updated the support matrix to be TS 5.4+ . As always, it's possible RTK will work if you're using an earlier version of TS, but we don't test against earlier versions and don't support any issues with those versions.
We have run an initial test with the upcoming TS 7.0 native tsgo release. We found a couple minor issues with our own TS build and test setup, but no obvious issues with using RTK with TS 7.0.
A user reported a rare edge case where the combination of resetApiState and retry() could lead to an error calling an AbortController. We've restructured our AbortController handling logic to avoid that (and simplified a bit of our internals in the process).
- Use trusted publishing and harden workflows by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5152
- Update TS typecheck matrix and add TS native job by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5155
- Officially document TS support by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5158
- Tweaks to AbortSignal logic by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/5150
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.11.0...v2.11.1
@rtk-query/codegen-openapi@2.2.0
This feature release adds new RTKQ codegen config options for outputting regex constants when the pattern keyword is used in an OpenAPI definition, and defining explicit tag overrides on a per-endpoint basis as part of the codegen config.
- feat: (codegen) output regex patterns for generated schemas by @RhysOnlyBetter in https://github.com/reduxjs/redux-toolkit/pull/5146
- feat(codegen): support explicit tag overrides without altering defaults by @w3di in https://github.com/reduxjs/redux-toolkit/pull/5135
- Add test for #3369 by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5154
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/@rtk-query/codegen-openapi@2.1.0...@rtk-query/codegen-openapi@2.2.0
v2.11.0
This feature release upgrades our Immer dependency to v11 to pick up the additional recent performance optimizations, adds a new refetchCachedPages option to allow only fetching the first cached page, and fixes an issue with regex ignore paths in the immutability middleware.
As described in the release notes for v2.10.0, we recently put significant effort into profiling Immer, and contributed several PRs that aimed to optimize its update performance.
v2.10.0 updated to use Immer 10.2.0, which added the first smaller set of perf updates. That included a new Immer option to disable "strict iteration" to speed up iterating copied objects, and we specifically applied that change in RTK under the assumption that standard plain JS objects as Redux state shouldn't have unusual keys anyway. Overall, this appears to boost Immer update perf by ~+20% over v10.1 depending on update scenario.
Immer v11.0.0 was just released and contains the second perf PR, a major internal architectural rewrite to change the update finalization implementation from a recursive tree traversal to a set of targeted updates based on accessed and updated fields. Based on the benchmarks in the PR, this adds another ~+5% perf boost over the improvements in v10.2, again with variations depending on update scenario. In practice, the actual improvement may be better than that - the benchmarks list includes some array update cases which actually got a bit slower (and thus drag down the overall average), and a majority of update scenarios show anywhere from +25% to +60% faster than Immer v10.1!
As a practical example, we have an RTK Query stress test benchmark where we mount 1000 components with query hooks at once, unmount, then remount them. We ran the same benchmark steps for RTK 2.9 and Immer 10.1, and then RTK 2.10+ and Immer 11. The overall scripting time dropped by about 30% (3330ms -> 2350ms), and the amount of time spent in Immer methods and the RTK reducers dropped significantly:
Based on this, it appears to be a major improvement overall.
As with the instructions in v2.10.0: if by some chance your Redux app state relies on non-string keys, you can still manually call setUseStrictIteration(true) in your app code to retain compatibility there, but we don't expect that standard Redux apps will have to worry about that.
There are still two outstanding Immer perf PRs that may offer further improvements: one that adds an optional plugin to override array methods to avoid proxy creation overhead, and another experimental tweak to shallow copying that may be better with larger object sizes.
RTK Query's infinite query API was directly based on React Query's approach, including the pages cache structure and refetching behavior. By default, that means that when you trigger a refetch, both R-Q and RTKQ will try to sequentially refetch all pages currently in that cache entry. So, if there were 5 pages cached for an entry, they will try to fetch pages 0...4, in turn.
Some users have asked for the ability to only refetch the first page. This can be accomplished somewhat manually by directly updating the cache entry to eliminate the old pages and then triggering a refetch, but that's admittedly not very ergonomic.
We've merged a contributed PR that adds a new refetchCachedPages flag. This can be defined as part of infinite query endpoints, passed as an option to infinite query hooks, or passed as an option in initiate() calls or hook refetch() methods. If set to refetchCachedPages: false, it will only refetch the first page in the cache and not the remaining pages, thus shrinking the cache from N pages to 1 page.
We merged a fix to the immutability dev middleware where it was treating ignoredPath regexes as strings and not actually testing them correctly.
- Update Immer to v11 for better update performance by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5141
- fix: compare paths against Regex instances in ignoredPaths by @johnste in https://github.com/reduxjs/redux-toolkit/pull/5124
- Add refetchCachedPages option for infinite query by @rossmartin in https://github.com/reduxjs/redux-toolkit/pull/5016
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.10.1...v2.11.0
v2.10.1
This bugfix release fixes an issue with window access breaking in SSR due to the byte-shaving work in 2.10.
- Fix window SSR breakage by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5132
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.10.0...v2.10.1
v2.10.0
This feature release updates our Immer dep to 10.2 to pick up its performance improvements, has additional byte-shaving and internal performance updates, and fixes a combineSlices type issue.
Redux Toolkit has been built around Immer since the very first prototype in 2018. Use of Immer as the default in createSlice directly eliminated accidental mutations as a class of errors in Redux apps, and drastically simplified writing immutable updates in reducers.
We've had various issues filed over the years asking to make Immer optional, or raising concerns about Immer's perf. Immer is indeed slower than writing immutable updates by hand, but our stance has always been that Immer's DX is absolutely worth whatever modest perf cost it might incur, and that reducers are usually not the bottleneck in Redux apps anyway - it's usually the cost of updating the UI that's more expensive.
However, a year ago an issue was filed with some specific complaints about Immer perf being very slow. We investigated, ran benchmarks, and filed an Immer issue confirming that it had gotten noticeably slower over time. Immer author Michel Weststrate agreed, and said there were some potential tweaks and architectural changes that could be made, but didn't have time to look into them himself.
A couple months ago, we started investigating possible Immer perf improvements ourselves, including profiling various scenarios and comparing implementations of other similar immutable update libraries. After extensive research and development, we were able to file several PRs to improve Immer's perf: a set of smaller tweaks around iteration and caching, a couple much larger architectural changes, and a potential change to copying objects.
Immer 10.2.0 contains the first set of smaller perf improvements, and this RTK release updates our dependency to 10.2 to pick up those changes.
One important behavior note here: Earlier versions of Immer (8, 9, 10.1) added more handling for edge cases like symbol keys in objects. These changes made sense for correctness, but also contributed to the slowdown. Immer 10.2 now includes a new setUseStrictIteration option to allow only copying string keys in objects (using Object.keys() instead of Reflect.ownKeys()), but keeps the option as strict: true for compatibility with its own users. That default will likely change in Immer 11.
For RTK 2.10.0, we specifically import and call setUseStrictIteration(false), under the assumption that standard Redux state usage only involves string keys in plain JS objects! This should provide a ~10% speedup for Immer update operations. Given that expectation, we believe this is a reasonable feature change and only needs a minor version bump.
If by some chance you are using symbol keys in your Redux state, or in other Immer-powered updates in your Redux app, you can easily revert to the previous behavior by calling setUseStrictIteration(true) in your own app code.
Based on discussions with Michel, Immer v11 should come out in the near future with additional architectural changes for better perf, including optional support for faster array methods that would be available as an Immer plugin adding ~2KB bundle size. We will likely not turn that plugin on by default, but recommend that users enable it if they do frequent array ops in reducers.
We're happy to have contributed these perf improvements to Immer, and that they will benefit not just RTK users but all Immer users everywhere!
You can follow the additional discussion and progress updates in the main Immer perf update tracking issue.
We've tweaked some places where we were doing repeated filter().map().map() calls to micro-optimize those loops.
RTKQ tag invalidation was always reading from proxy-wrapped arrays when rewriting provided tags. It now reads from the plain arrays instead, providing a modest speedup.
We previously found that ESBuild wasn't deduplicating imports from the same libraries in separate files bundled together (ie import { useEffect as useEffect2/3/4/ } from 'react'). We've restructured our internals to ensure all external imports are only pulled in once.
We've done some extensive byte-shaving in various places in the codebase. The byte-shaving and import deduplication saves about 0.6K min from the RTKQ core, and 0.2K min from the RTKQ React bundle.
combineSlices now better handles cases where PreloadedState might not match the incoming type, such as persisted values.
- Improve perf for internal map/filter ops by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5126
- Update Immer dep to 10.2 and disable strict iteration for perf by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5127
- Deduplicate imports by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5128
- Byte-shave various chunks of code by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5129
- fix(combineSlices): Infer PreloadedState properly from provided slice by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/5125
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.9.2...v2.10.0