NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm · #1887 most downloaded on npm
The official, opinionated, batteries-included toolset for efficient Redux development
Last release 5 days ago
29 Sep 2026
Release timing varies
gaps range from 2 weeks to 5 months
Nearly every release is documented
notes for 58 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
7 years old
117 releases · first in 2019
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
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.
pkg.pr.new by @aryaemami59 in #5256entityAdapter): setAll with duplicate IDs keeps last occurrence (consistent with setMany) by @JSap0914 in #5321createAsyncThunk aborts that happen before pending by @chatman-media in #5314useRef<T | undefined>(undefined) usages in RTK Query hooks by @DucMinhNe in #5315onQueryStarted from triggering at end-of-list by @joseph0926 in #5182remark-typescript-tools and update to TS7 by @markerikson in #5390rejectedWithValue for falsy rejectWithValue payloads by @dfedoryshchev in #5395immutableStateInvariantMiddleware by @hamed-bavar in #5433useQueryState and isSuccess during refetch-after-error by @markerikson in #5456Full Changelog: v2.12.0...v2.13.0
One column per quarter.
This feature release adds RTK usage skills files (via TanStack Intent) exports the RTK Query hook options types for reusability, fixes issues with inf
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.
IgnorePaths type to IgnoredPaths by @Ri5ha6h in #5284NoInfer utility type by @aryaemami59 in #5289Full Changelog: v2.11.2...v2.12.0
This bugfix release updates the AbortSignal handling to fall back if DOMException isn't available (such as RN environments), and updates the TypedUseI
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.
TypedUseInfiniteQueryHookResult by @markerikson in #5165Full Changelog: v2.11.1...v2.11.2
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
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:
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).
Full Changelog: v2.11.0...v2.11.1
This feature release upgrades our Immer dependency to v11 to pick up the additional recent performance optimizations, adds a new refetchCachedPages op
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.
refetchCachedPages OptionRTK 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.
Full Changelog: v2.10.1...v2.11.0
This bugfix release fixes an issue with window access breaking in SSR due to the byte-shaving work in 2.10.
This bugfix release fixes an issue with window access breaking in SSR due to the byte-shaving work in 2.10.
Full Changelog: v2.10.0...v2.10.1
This feature release updates our Immer dep to 10.2 to pick up its performance improvements, has additional byte-shaving and internal performance updat
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.
Full Changelog: v2.9.2...v2.10.0
This bugfix release fixes a potential internal data leak in SSR environments, improves handling of headers in fetchBaseQuery , improves retry handling
This bugfix release fixes a potential internal data leak in SSR environments, improves handling of headers in fetchBaseQuery, improves retry handling for unexpected errors and request aborts, and fixes a longstanding issue with prefetch leaving an unused subscription. We've also shipped a new graphqlRequestBaseQuery release with updated dependencies and better error handling.
We had a report that a Redux SSR app had internal subscription data showing up across different requests. After investigation, this was a bug introduced by the recent RTKQ perf optimizations, where the internal subscription fields were hoisted outside of the middleware setup and into createApi itself. This meant they existed outside of the per-store-instance lifecycle. We've reworked the logic to ensure the data is per-store again. We also fixed another issue that miscalculated when there was an active request while checking for cache entry cleanup.
Note that no actual app data was leaked in this case, just the internal subscription IDs that RTKQ uses in its own middleware to track the existence of subscriptions per cache entry.
fetchBaseQuery HeadersWe've updated fetchBaseQuery to avoid setting content-type in cases where a non-JSONifiable value like FormData is being passed as the request body, so that the browser can set that content type itself. It also now sets the accept header based on the selected responseHandler (JSON or text).
retry Behavior and CleanupThe retry util now respects the maxRetries option when catching unknown errors in addition to the existing known errors logic. It also now checks the request's AbortSignal and will stop retrying if aborted.
In conjunction with that, dispatching resetApiState will now abort all in-flight requests.
The prefetch util and usePrefetch hook had a long-standing issue where they would create a subscription for a cache entry, but there was no way to clean up that subscription. This meant that the cache entry was effectively permanent. They now initiate the request without adding a subscription. This will fetch the cache entry and leave it in the store for the keepUnusedDataFor period as intended, giving your app time to actually subscribe to the value (such as prefetching the cache entry in a route handler, and then subscribing in a component).
graphqlRequestBaseQueryWe've published @rtk-query/graphql-request-base-query v2.3.2, which updates the graphql-request dep to ^7. We also fixed an issue where the error handling rethrew unknown errors - it now returns {error} as a base query is supposed to.
fetchBaseQuery default headers handling by @markerikson in #5112retry abort handling and abort on resetApiState by @markerikson in #5114Full Changelog: v2.9.1...v2.9.2
This bugfix release fixes how sorted entity adapters handle duplicate IDs, tweaks the TS types for RTKQ query state cache entries to improve how the d
This bugfix release fixes how sorted entity adapters handle duplicate IDs, tweaks the TS types for RTKQ query state cache entries to improve how the data field is handled, and adds better cleanup for long-running listener middleware effects.
data on isSuccess with exactOptionalPropertyTypes by @CO0Ki3 in https://github.com/reduxjs/redux-toolkit/pull/5088listenerMiddleware.clearListeners by @chris-chambers in https://github.com/reduxjs/redux-toolkit/pull/5102Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.9.0...v2.9.1
This feature release rewrites RTK Query's internal subscription and polling systems and the useStableQueryArgs hook for better perf, adds automatic Ab
This feature release rewrites RTK Query's internal subscription and polling systems and the useStableQueryArgs hook for better perf, adds automatic AbortSignal handling to requests still in progress when a cache entry is removed, fixes a bug with the transformResponse option for queries, adds a new builder.addAsyncThunk method, and fixes assorted other issues.
We had reports that RTK Query could get very slow when there were thousands of subscriptions to the same cache entry. After investigation, we found that the internal polling logic was attempting to recalculate the minimum polling time after every new subscription was added. This was highly inefficient, as most subscriptions don't change polling settings, and it required repeated O(n) iteration over the growing list of subscriptions. We've rewritten that logic to debounce the update check and ensure a max of one polling value update per tick for the entire API instance.
Related, while working on the request abort changes, testing showed that use of plain Records to hold subscription data was inefficient because we have to iterate keys to check size. We've rewritten the subscription handling internals to use Maps instead, as well as restructuring some additional checks around in-flight requests.
These two improvements drastically improved runtime perf for the thousands-of-subscriptions-one-cache-entry repro, eliminating RTK methods as visible hotspots in the perf profiles. It likely also improves perf for general usage as well.
We've also changed the implementation of our internal useStableQueryArgs hook to avoid calling serializeQueryArgs on its value, which can avoid potential perf issues when a query takes a very large object as its cache key.
[!NOTE] The internal logic switched from serializing the query arg to doing reference checks on nested values. This means that if you are passing a non-POJO value in a query arg, such as
useSomeQuery({a: new Set()}), and you haverefetchOnMountOrArgChangeenabled, this will now trigger refeteches each time as theSetreferences are now considered different based on equality instead of serialization.
We've had numerous requests over time for various forms of "abort in-progress requests when the data is no longer needed / params change / component unmounts / some expensive request is taking too long". This is a complex topic with multiple potential use cases, and our standard answer has been that we don't want to abort those requests - after all, cache entries default to staying in memory for 1 minute after the last subscription is removed, so RTKQ's cache can still be updated when the request completes. That also means that it doesn't make sense to abort a request "on unmount".
However, it does then make sense to abort an in-progress request if the cache entry itself is removed. Given that, we've updated our cache handling to automatically call the existing resPromise.abort() method in that case, triggering the AbortSignal attached to the baseQuery. The handling at that point depends on your app - fetchBaseQuery should handle that, a custom baseQuery or queryFn would need to listen to the AbortSignal.
We do have an open issue asking for further discussions of potential abort / cancelation use cases and would appreciate further feedback.
The builder callback used in createReducer and createSlice.extraReducers now has builder.addAsyncThunk available, which allows handling specific actions from a thunk in the same way that you could define a thunk inside createSlice.reducers:
const slice = createSlice({
name: 'counter',
initialState: {
loading: false,
errored: false,
value: 0,
},
reducers: {},
extraReducers: (builder) =>
builder.addAsyncThunk(asyncThunk, {
pending(state) {
state.loading = true
},
fulfilled(state, action) {
state.value = action.payload
},
rejected(state) {
state.errored = true
},
settled(state) {
state.loading = false
},
}),
})
createApi and individual endpoint definitions now accept a skipSchemaValidation option with an array of schema types to skip, or true to skip validation entirely (in case you want to use a schema for its types, but the actual validation is expensive).
The infinite query implementation accidentally changed the query internals to always run transformResponse if provided, including if you were using upsertQueryData(), which then broke. It's been fixed to only run on an actual query request.
The internal changes to the structure of the state.api.provided structure broke our handling of extractRehydrationInfo - we've updated that to handle the changed structure.
The infinite query status fields like hasNextPage are now a looser type of boolean initially, rather than strictly false.
We now export Immer's WritableDraft type to fix another non-portable types issue.
We've added an api.endpoints.myEndpoint.types.RawResultType types-only field to match the other available fields.
transformResponse when a query is used by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5049Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.8.2...v2.9.0
This bugfix release fixes a bundle size regression in RTK Query from the build and packaging changes in v2.8.0.
This bugfix release fixes a bundle size regression in RTK Query from the build and packaging changes in v2.8.0.
If you're using v2.8.0 or v2.8.1, please upgrade to v2.8.2 right away to resolve that bundle size issue!
In v2.8.0, we reworked our packaging setup to better support React Native. While there weren't many meaningful code changes, we did alter our bundling build config file. In the process, we lost the config options to externalize the @reduxjs/toolkit core when building the RTK Query nested entry points. This resulted in a regression where the RTK core code also got bundled directly into the RTK Query artifacts, resulting in a significant size increase.
This release fixes the build config and restores the previous RTKQ build artifact sizes.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.8.1...v2.8.2
This bugfix release makes an additional update to the package config to fix a regression that happened with Jest and jest-environment-jsdom.
This bugfix release makes an additional update to the package config to fix a regression that happened with Jest and jest-environment-jsdom.
[!CAUTION] This release had a bundle size regression. Please update to v2.8.2 to resolve that issue.
After releasing v2.8.0, we got reports that Jest tests were breaking. After investigation we concluded that jest-environment-jsdom was looking at the new browser package exports condition we'd added to better support JSPM, finding an ESM file containing the export keyword, and erroring because it doesn't support ES modules correctly.
https://github.com/reduxjs/redux-toolkit/issues/4971#issuecomment-2859506562 listed several viable workarounds, but this is enough of an issue we wanted to fix it directly. We've tweaked the package exports setup again, and it appears to resolve the issue with Jest.
browser exports condition by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4973Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.8.0...v2.8.1
This feature release improves React Native compatibility by updating our package exports definitions, and adds queryArg as an additional parameter to
This feature release improves React Native compatibility by updating our package exports definitions, and adds queryArg as an additional parameter to infinite query page param functions.
[!CAUTION] This release had a bundle size regression, as well as a breakage with
jest-environment-jsdom. Please update to v2.8.2 to resolve those issues.
Expo and the Metro bundler have been adding improved support for the exports field in package.json files, but those changes started printing warnings due to how some of our package definitions were configured.
We've reworked the package definitions (again!), and this should be resolved now.
The signature for the getNext/PreviousPageParam functions has been:
(
lastPage: DataType,
allPages: Array<DataType>,
lastPageParam: PageParam,
allPageParams: Array<PageParam>,
) => PageParam | undefined | null
This came directly from React Query's API and implementation.
We've had some requests to make the endpoint's queryArg available in page param functions. For React Query, that isn't necessary because the callbacks are defined inline when you call the useInfiniteQuery hook, so you've already got the query arg available in scope and can use it. Since RTK Query defines these callbacks as part of the endpoint definition, the query arg isn't in scope.
We've added queryArg as an additional 5th parameter to these functions in case it's needed.
We've made a few assorted docs updates, including replacing the search implementation to now use a local index generated on build (which should be more reliable and also has a nicer results list uI), and fixing some long-standing minor docs issues.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.7.0...v2.8.0
RTK has hit Stage 2.7! :rofl: This feature release adds support for Standard Schema validation in RTK Query endpoints, fixes several issues with infin
RTK has hit Stage 2.7! :rofl: This feature release adds support for Standard Schema validation in RTK Query endpoints, fixes several issues with infinite queries, improves perf when infinite queries provide tags, adds a dev-mode check for duplicate middleware, and improves reference stability in slice selectors and infinite query hooks.
Apps often need to validate responses from the server, both to ensure the data is correct, and to help enforce that the data matches the expected TS types. This is typically done with schema libraries such as Zod, Valibot, and Arktype. Because of the similarities in usage APIs, those libraries and others now support a common API definition called Standard Schema, allowing you to plug your chosen validation library in anywhere Standard Schema is supported.
RTK Query now supports using Standard Schema to validate query args, responses, and errors. If schemas are provided, the validations will be run and errors thrown if the data is invalid. Additionally, providing a schema allows TS inference for that type as well, allowing you to omit generic types from the endpoint.
Schema usage is per-endpoint, and can look like this:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import * as v from 'valibot'
const postSchema = v.object({
id: v.number(),
name: v.string(),
})
type Post = v.InferOutput<typeof postSchema>
const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: (build) => ({
getPost: build.query({
// infer arg from here
query: ({ id }: { id: number }) => `/post/${id}`,
// infer result from here
responseSchema: postSchema,
}),
getTransformedPost: build.query({
// infer arg from here
query: ({ id }: { id: number }) => `/post/${id}`,
// infer untransformed result from here
rawResponseSchema: postSchema,
// infer transformed result from here
transformResponse: (response) => ({
...response,
published_at: new Date(response.published_at),
}),
}),
}),
})
If desired, you can also configure schema error handling with the catchSchemaFailure option. You can also disable actual runtime validation with skipSchemaValidation (primarily useful for cases when payloads may be large and expensive to validate, but you still want to benefit from the TS type inference).
See the "Schema Validation" docs section in the createApi reference and the usage guide sections on queries, infinite queries, and mutations, for more details.
This release fixes several reported issue with infinite queries:
lifecycleApi.updateCachedData method is now correctly availableskip option now correctly works for infinite query hooksfulfilled actions now include the meta field from the base query (such as {request, response}). For cases where multiple pages are being refetched, this will be the meta from the last page fetched.useInfiniteQuerySubscription now returns stable references for refetch and the fetchNext/PreviousPage methodsupsertQueryEntries, Tags Performance and API State StructureWe recently published a fix to actually process per-endpoint providedTags when using upsertQueryEntries. However, this exposed a performance issue - the internal tag handling logic was doing repeated O(n) iterations over all endpoint+tag entries in order to clear out existing references to that cache key. In cases where hundreds or thousands of cache entries were being inserted, this became extremely expensive.
We've restructured the state.api.provided data structure to handle reverse-mapping between tags and cache keys, which drastically improves performance in this case. However, it's worth noting that this is a change to that state structure. This shouldn't affect apps, because the RTKQ state is intended to be treated as a black box and not generally directly accessed by user app code. However, it's possible someone may have depended on that specific state structure when writing a custom selector, in which case this would break. An actual example of this is the Redux DevTools RTKQ panel, which iterates the tags data while displaying cache entries. That did break with this change. Prior to releasing RTK 2.7,we released Redux DevTools 3.2.10, which includes support for both the old and new state.api.provided definitions.
Following with the DefinitelyTyped support matrix, we've officially dropped support for TS 5.0, and currently support TS 5.1 - 5.8. (RTK likely still works with 5.0, but we no longer test against that in CI.)
configureStore now checks the final middleware array for duplicate middleware references. This will catch cases such as accidentally adding the same RTKQ API middleware twice (such as adding baseApi.middleware and injectedApi.middlweware - these are actually the same object and same middleware).
Unlike the other dev-mode checks, this is part of configureStore itself, not getDefaultMiddleware().
This can be configured via the new duplicateMiddlewareCheck option.
createEntityAdapter now correctly handles adding an item and then applying multiple updates to it.
The generated combineSlices selectors will now return the same placeholder initial state reference for a given slice, rather than returning a new initial state reference every time.
useQuery hooks should now correctly refetch after dispatching resetApiState.
useQuery hook does not refetch after resetApiState by @juniusfree in https://github.com/reduxjs/redux-toolkit/pull/4758catchSchemaFailure, and docs for RTKQ schema features by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/4934Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.6.1...v2.7.0
This bugfix release fixes several assorted types issues with the initial infinite query feature release, and adds support for an optional signal argum
This bugfix release fixes several assorted types issues with the initial infinite query feature release, and adds support for an optional signal argument to createAsyncThunk.
We've fixed several types issues that were reported with infinite queries after the 2.6.0 release:
matchFulfilled and providesTags now get the correct response typesType* types to represent infinite queries, similar to the existing pre-defined types for queries and mutationsselectCachedArgsForQuery now supports fetching args for infinite query endpointsuseInfiniteQueryState/Subscription now correctly expect just the query arg, not the combined {queryArg, pageParam} objectcreateAsyncThunk now accepts an optional {signal} argument. If provided, the internal AbortSignal handling will tie into that signal.
upsertQueryEntries now correctly generates provided tags for upserted cache entries.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.6.0...v2.6.1
This feature release adds infinite query support to RTK Query.
This feature release adds infinite query support to RTK Query.
Since we first released RTK Query in 2021, we've had users asking us to add support for "infinite queries" - the ability to keep fetching additional pages of data for a given endpoint. It's been by far our most requested feature. Until recently, our answer was that we felt there were too many use cases to support with a single API design approach.
Last year, we revisited this concept and concluded that the best approach was to mimic the flexible infinite query API design from React Query. We had additional discussions with @tkdodo , who described the rationale and implementation approach and encouraged us to use their API design, and @riqts provided an initial implementation on top of RTKQ's existing internals.
We're excited to announce that this release officially adds full infinite query endpoint support to RTK Query!
As with React Query, the API design is based around "page param" values that act as the query arguments for fetching a specific page for the given cache entry.
Infinite queries are defined with a new build.infiniteQuery() endpoint type. It accepts all of the same options as normal query endpoints, but also needs an additional infiniteQueryOptions field that specifies the infinite query behaviors. With TypeScript, you must supply 3 generic arguments: build.infiniteQuery<ResultType, QueryArg, PageParam>, where ResultType is the contents of a single page, QueryArg is the type passed in as the cache key, and PageParam is the value used to request a specific page.
The endpoint must define an initialPageParam value that will be used as the default (and can be overridden if desired). It also needs a getNextPageParam callback that will calculate the params for each page based on the existing values, and optionally a getPreviousPageParam callback if reverse fetching is needed. Finally, a maxPages option can be provided to limit the entry cache size.
The query and queryFn methods now receive a {queryArg, pageParam} object, instead of just the queryArg.
For the cache entries and hooks, the data field is now an object like {pages: ResultType[], pageParams: PageParam[]>. This gives you flexibility in how you use the data for rendering.
const pokemonApi = createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/pokemon' }),
endpoints: (build) => ({
// 3 TS generics: page contents, query arg, page param
getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({
infiniteQueryOptions: {
// Must provide a default initial page param value
initialPageParam: 1,
// Optionally limit the number of cached pages
maxPages: 3,
// Must provide a `getNextPageParam` function
getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
lastPageParam + 1,
// Optionally provide a `getPreviousPageParam` function
getPreviousPageParam: (
firstPage,
allPages,
firstPageParam,
allPageParams,
) => {
return firstPageParam > 0 ? firstPageParam - 1 : undefined
},
},
// The `query` function receives `{queryArg, pageParam}` as its argument
query({ queryArg, pageParam }) {
return `/type/${queryArg}?page=${pageParam}`
},
}),
}),
})
As with all RTKQ functionality, the core logic is UI-agnostic and does not require React. However, using the RTKQ React entry point will also auto-generate useInfiniteQuery hooks for these endpoints. Infinite query hooks fetch the initial page, then provide fetchNext/PreviousPage functions to let you trigger requests for more pages.
function PokemonList({
pokemonType = 'fire',
}: {
pokemonType?: string
) {
const {
data,
isFetching,
isSuccess,
fetchNextPage,
fetchPreviousPage,
refetch,
} = api.useGetInfinitePokemonInfiniteQuery(pokemonType)
const handlePreviousPage = async () => {
const res = await fetchPreviousPage()
}
const handleNextPage = async () => {
const res = await fetchNextPage()
}
// `data` is a `{pages, pageParams}` object.
// You can use those to render whatever UI you need.
// In this case, flatten per-page arrays of results for this endpoint
// into a single array to render a list.
const allPokemon = data?.pages.flat() ?? [];
// render UI with pages, show loading state, fetch as needed
}
The RTK Query docs have been updated with new content and explanations for infinite queries:
createApi documents the new infinite query endpoint optionsWe've also added a new infinite query example app in the repo that shows several usage patterns like pagination, cursors, infinite scrolling, and limit+offset queries.
As with all new features and functionality, more code does mean an increase in bundle size.
We did extensive work to byte-shave and optimize the final bundle size for this feature. Final estimates indicate that this adds about 4.2Kmin to production bundles. That's comparable to React Query's infinite query support size.
However, given RTKQ's current architecture, that bundle size increase is included even if you aren't using any infinite query endpoints in your application. Given the significant additional functionality, that seems like an acceptable tradeoff. (And as always, having this kind of functionality built into RTKQ means that your app benefits when it uses this feature without having to add a lot of additional code to your own app, which would likely be much larger.)
Longer-term, we hope to investigate reworking some of RTKQ's internal architecture to potentially make some of the features opt-in for better bundle size optimizations, but don't have a timeline for that work.
This new feature wouldn't have been possible without huge amounts of assistance from several people. We'd like to thank:
and numerous specific sub-PRs that went into that integration PR as I worked through the implementation over the last few months.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.5.1...v2.6.0
This bugfix release fixes a logic issue with the new upsertQueryEntries util that sometimes kept entries in a pending state indefinitely.
This bugfix release fixes a logic issue with the new upsertQueryEntries util that sometimes kept entries in a pending state indefinitely.
upsertQueryEntries fixesUsers reported that in some cases, use of upsertQueryEntries to insert RTKQ cache entries prevented any further refetches of that data from happening. After investigation, we found a logic mismatch for how we handle upserts vs the existing upsertQueryData util, which meant that sometimes the entry would be left in a pending state expecting a fulfilled action from a request ID that would never happen.
This release fixes that issue and ensures the updates and refetches happen correctly.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.5.0...v2.5.1
This feature release updates the React peer dependency to work with React 19, and fixes an additional skip token issue.
This feature release updates the React peer dependency to work with React 19, and fixes an additional skip token issue.
React 19 was just released! We've updated our peer dep to accept React 19, and updated our runtime and type tests to check against both React 18 and 19.
Also see React-Redux v9.2.0 for the same peer dep update.
We previously fixed an issue with the RTKQ core where serializeQueryArgs callbacks could be called with skipToken, potentially leading to errors. We've fixed an additional location in the useQuery hooks where that could happen as well.
serializeQueryArgs + skipToken case by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/4762Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.4.0...v2.5.0
This feature release includes multiple tweaks and fixes to RTK Query functionality, additional exported TS types, and drops support for TS versions ea
This feature release includes multiple tweaks and fixes to RTK Query functionality, additional exported TS types, and drops support for TS versions earlier than 5.0.
Lazy query hooks can now be reset.
retry.fail now accepts meta as a second argument.
Tag invalidation arrays now ignore nullish values.
We did some small internal refactoring around Maps and default values that shrank bundle size slightly.
Passing skipToken to a query hook now bails out before running any other logic, which fixes cases where serializeQueryArgs previously threw an error because there were no args to process.
The autoBatchEnhancer now reads window.requestAnimationFrame later, which it to work properly with Jest fake timers.
We fixed cases where the hook result isSuccess flag would briefly flicker to false when switched to a different cache entry that was uninitialized, and would briefly flicker to true when refetching a query that previously errored.
The listener middleware previously had inconsistent logic checks for comparing against existing listener entries (effect + type, vs effect only). It now always checks both effect + type.
We now export Typed[Query|Mutation]OnQueryStarted helpers to let you define onQueryStarted callbacks outside of createApi if desired.
We also now export a CreateAsyncThunkFunction type that can be used to type userland wrappers around createAsyncThunk.
We've historically tried to maintain TS backwards compatibility as long as possible, and made occasional updates to our TS support matrix in minor versions over time. As of RTK 2.3.0, we officially supported back through TS 4.7.
As of this release, we're tweaking that support policy to match the policy used by DefinitelyTyped:
Definitely Typed only tests packages on versions of TypeScript that are less than 2 years old
Given that, we've dropped official support for TS versions earlier than 5.0. (RTK may work with those versions, but we no longer test against them and won't try to fix issues with those versions.)
We'll continue to update our TS support matrix over time based on that 2-year rolling window.
window.rAF later to allow fake timers to work correctly by @ensconced in https://github.com/reduxjs/redux-toolkit/pull/4701OnQueryStarted callbacks by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4713createAsyncThunk without the withTypes method by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/4667isSuccess: true when switching to an uninitialized cache entry by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/4731isSuccess consistent when refetching after an error by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/4732Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.3.0...v2.4.0
This feature release adds a new RTK Query upsertQueryEntries util to batch-upsert cache entries more efficiently, passes through additional values for
This feature release adds a new RTK Query upsertQueryEntries util to batch-upsert cache entries more efficiently, passes through additional values for use in prepareHeaders, and exports additional TS types around query options and selectors.
upsertQueryEntriesRTK Query already had an upsertQueryData thunk that would upsert a single cache entry. However, some users wanted to upsert many cache entries (potentially hundreds or thousands), and found that upsertQueryData had poor performance in those cases. This is because upsertQueryData runs the full async request handling sequence, including dispatching both pending and fulfilled actions, each of which run the main reducer and update store subscribers. That means there's 2N store / UI updates per item, so upserting hundreds of items becomes extremely perf-intensive.
RTK Query now includes an api.util.upsertQueryEntries action that is meant to handle the batched upsert use case more efficiently. It's a single synchronous action that accepts an array of many {endpointName, arg, value} entries to upsert. This results in a single store update, making this vastly better for performance vs many individual upsertQueryData calls.
We see this as having two main use cases. The first is prefilling the cache with data retrieved from storage on app startup (and it's worth noting that upsertQueryEntries can accept entries for many different endpoints as part of the same array).
The second is to act as a "pseudo-normalization" tool. RTK Query is not a "normalized" cache. However, there are times when you may want to prefill other cache entries with the contents of another endpoint, such as taking the results of a getPosts list endpoint response and prefilling the individual getPost(id) endpoint cache entries, so that components that reference an individual item endpoint already have that data available.
Currently, you can implement the "pseudo-normalization" approach by dispatching upsertQueryEntries in an endpoint lifecycle, like this:
const api = createApi({
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => '/posts',
async onQueryStarted(_, { dispatch, queryFulfilled }) {
const res = await queryFulfilled
const posts = res.data
// Pre-fill the individual post entries with the results
// from the list endpoint query
dispatch(
api.util.upsertQueryEntries(
posts.map((post) => ({
endpointName: 'getPost',
arg: { id: post.id },
value: post,
})),
),
)
},
}),
getPost: build.query<Post, Pick<Post, 'id'>>({
query: (post) => `post/${post.id}`,
}),
}),
})
Down the road we may add a new option to query endpoints that would let you provide the mapping function and have it automatically update the corresponding entries.
For additional comparisons between upsertQueryData and upsertQueryEntries, see the upsertQueryEntries API reference.
prepareHeaders OptionsThe prepareHeaders callback for fetchBaseQuery now receives two additional values in the api argument:
arg: the URL string or FetchArgs object that was passed in to fetchBaseQuery for this endpointextraOptions: any extra options that were provided to the base queryWe've added a TypedQueryStateSelector type that can be used to pre-type selectors for use with selectFromResult:
const typedSelectFromResult: TypedQueryStateSelector<
PostsApiResponse,
QueryArgument,
BaseQueryFunction,
SelectedResult
> = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
function PostsList() {
const { posts } = useGetPostsQuery(undefined, {
selectFromResult: typedSelectFromResult,
})
}
We've also exported several additional TS types around base queries and tag definitions.
TypedQueryStateSelector helper type by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4656Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.8...v2.3.0
This bugfix release fixes a long-standing issue with RTK Query lazy query triggers returning stale data in some cases, fixes an error handling issue i
This bugfix release fixes a long-standing issue with RTK Query lazy query triggers returning stale data in some cases, fixes an error handling issue in RTK Query, and exports additional TS types.
We'd had a couple long-standing issues reporting that const result = await someLazyQueryTrigger() sometimes returned stale data, especially if a mutation had just invalidated that query's tag.
We finally got a good repro of this issue and identified it as a mis-written call inside of the middleware that skipped past the necessary handling to activate the correct query status tracking in that scenario. This should now be fixed.
Timeout handling in RTKQ endpoints should now correctly throw a timeout-related error instead of an AbortError.
Base queries now have access to the current queryCacheKey value so it can be used in deciding query logic.
We've exported several more TS types related to query options, as some users have been depending on those even though they previously weren't part of the public API.
QueryExtraOptions and MutationExtraOptions by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4556mangleErrors not preserving different error types by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4586TypedUseQueryStateOptions helper type by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4604AbortError being triggered incorrectly on createApi endpoint timeout by @andrejpavlovic in https://github.com/reduxjs/redux-toolkit/pull/4628initiate to refetch queries from middleware by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/4651Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.7...v2.2.8
This bugfix release fixes issues with "TS type portability" errors, improves build artifact tree shaking behavior, and exports some additional TS type
This bugfix release fixes issues with "TS type portability" errors, improves build artifact tree shaking behavior, and exports some additional TS types.
We've had a slew of issues reported around "TS type portability" errors, such as:
The error messages are typically along the lines of:
Type error: The inferred type of
'configureStore'cannot be named without a reference to'@reduxjs/toolkit/node_modules/redux'. This is likely not portable. A type annotation is necessary.
@aryaemami59 did some deep investigation and concluded these were due to a mixture of using interface instead of type in most places, not pre-bundling our TS typedefs, and not exporting some of the unique symbols we use internally.
Arya put together a highly detailed writeup and set of fixes in #4467: Fix: TypeScript Type Portability Issues, and that appears to resolve all of those issues we've seen. Thank you!
Arya also did significant work to improve RTK's treeshaking, tweaking internal definitions to let bundlers better separate out unused code.
We've exported additional types like UpdateDefinitions and RetryOptions, per request.
listenerMiddleware.withTypes() methods now allow passing in an ExtraArgument generic.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.6...v2.2.7
Brings internal useIsomorphicLayoutEffect usage in line with React Redux in React Native environments
This bugfix release:
useIsomorphicLayoutEffect usage in line with React Redux in React Native environmentsFetchBaseQueryArgs typecreateEntityAdapter sorting perf improvements that could (in specific cases) cause Immer to throw an erroruseIsomorphicLayoutEffect usage in React Native environments by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4436Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.5...v2.2.6
This bugfix release fixes an issue in the recent createEntityAdapter sorting perf improvements that could (in specific cases) cause Immer to throw an
This bugfix release fixes an issue in the recent createEntityAdapter sorting perf improvements that could (in specific cases) cause Immer to throw an error when trying to read a plain JS value instead of a proxy-wrapped value.
current may fail if the value is not a draft by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/4412Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.4...v2.2.5
Inline the deprecated React.ReactChild type by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4382
This bugfix release improves sorting performance in createEntityAdapter, shrinks the code size in matcher utilities, fixes assorted issues with query hooks, and makes several TS tweaks.
Users reported in #4252 that the sorting performance of createEntityAdapter seemed abnormally bad - the provided comparison functions were being called far more times than expected.
Upon investigation, we had a couple of problems. We were always starting from an array that was in insertion order, not the existing sorted order, and that would always require significant effort to re-sort even if there weren't any actual changes to the sorted results. Also, the sorting checks required frequent access to Immer's Proxy-wrapped values, even in cases where all we needed was the plain state values for comparison purposes.
We've reworked the internal sorting logic to always start from the existing sorted array, do reads against a plain value to avoid the Proxy getter overhead where possible, and optimized inserts into existing sorted arrays. This should significantly speed up sorted entity adapter behavior.
We've reworked the internals of the thunk-related matchers to deduplicate some of the logic, shaving a few bytes off the final bundle size.
defaultSerializeQueryArgs can now handle BigInt values safely.
The isLoading flag logic was improved to handle errors when a query hook tries to subscribe.
create.asyncThunk's types were improved to avoid cases where it might infer any.
We've made several internal types changes to work correctly with React 19's upcoming types.
The retryCondition method now receives unknown as an argument, instead of always assuming the user is using fetchBaseQuery.
The Reselect dep has been bumped to 5.1.0 to match the expected internal usage of createSelector.withTypes().
Context references to match the new nullable Context by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4336GetThunkAPI type by @shrouxm in https://github.com/reduxjs/redux-toolkit/pull/4289React.ReactChild type by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4382JSX global namespace with React.JSX by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4381useRef usages to be called with an explicit argument of undefined. by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4380reselect dependency to 5.1.0 to resolve #4200 by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4400initiate() action for mutations. by @jared-ca in https://github.com/reduxjs/redux-toolkit/pull/4337Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.3...v2.2.4
This bugfix release fixes the types for functions that accept a React Context instance to match the changes in React Redux v9.
This bugfix release fixes the types for functions that accept a React Context instance to match the changes in React Redux v9.
.withTypes by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4308Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.2...v2.2.3
rename TypedUseMutationTrigger to TypedMutationTrigger, and add deprecated alias by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/4204
This patch release fixes an incorrect build setting for the legacy-esm artifacts, and fixes an issue with RTKQ query hooks didn't always remove the cache entries if arguments were changed rapidly.
legacy-esm Artifact TranspilationThe legacy-esm build artifacts are intended for use by Webpack 4. Those were supposed to be transpiled to target "es2017", but were in fact still set to target "esnext" - an oversight during the 2.0 development cycle. This release fixes that setting, so those artifacts are now correctly transpiled.
RTKQ query hooks now handle additional actions around argument changes that should result in cache entries being removed.
Additionally, 2.2.1 contained a fix to an incorrectly named type: TypedUseMutationTrigger is now TypedMutationTrigger.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.2.0...v2.2.2
Nothing published for this version
Adds a second parameter to entityAdapter.getInitialState(additionalProps, entities) to allow prefilling state
This minor release:
entityAdapter.getInitialState(additionalProps, entities) to allow prefilling state
entityAdapter.setAll(entityAdapter.getInitialState(additionalProps), entities)undefined if no additional properties are desiredcombineSlices with no static reducers
const combinedReducer = combineSlices().withLazyLoadedSlices<LazyLoadedSlices>() would have thrown an error'throw' value for overrideExisting in injectEndpoints, which throws an error if a definition is injected with a name which is already usedenhanceEndpointsLazyLoadedSlices)action.meta.arg.isPrefetch value to query thunk actions when prefetchedcli.js to cli.mjs by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4169withLazyLoadedSlices by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4172overrideExisting by @ffluk3 in https://github.com/reduxjs/redux-toolkit/pull/4189tsconfig.json files of all CodesandBox examples by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4190Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.1.0...v2.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.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/@rtk-query/codegen-openapi@2.1.0...@rtk-query/codegen-openapi@2.2.0
This feature release adds new RTK Query codegen config options for useUnknown and esmExtensions, update the hook name generation to make use of operat
This feature release adds new RTK Query codegen config options for useUnknown and esmExtensions, update the hook name generation to make use of operationNameSuffix if available, fixes an issue with falsy query params, adds the CLI binary to the list of exports, and updates the swagger-parser dep to give support for OpenAPI v3.0.4
We've added two new config options:
useUnknown: if enabled, tells the underlying oazapfts library to use unknown as a fallback type instead of any (per https://github.com/oazapfts/oazapfts/issues/676 )esmExtensions: if enabled, import statements will use the appropriate compiled file extension explicitly (such as import { api } from 'emptyApi.mjs')Fixed an issue where encodeQueryParams: true would omit falsy values like 0 entirely, instead of encoding them as someValue=.
Hook names now include the operationNameSuffix if specified for that endpoint.
The package CLI is now properly listed in the package.json exports.
The @apidevtools/swagger-parser dependency was updated, which should enable support for OpenAPI v3.0.4 format files.
@apidevtools/swagger-parser to version 10.1.1 by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4919operationNameSuffix when provided by @lcharlois-neotys in https://github.com/reduxjs/redux-toolkit/pull/5089Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/@rtk-query/codegen-openapi@2.0.0...@rtk-query/codegen-openapi@2.1.0
This minor release:
listenerMiddleware and createDraftSafeSelectorskipPollingIfUnfocused option to RTK QuerycreateSelector instance used by RTK Querythis valuecreate.asyncThunk type parametersqueryFnslistenerMiddleware.withTypes<RootState, AppDispatch>() method by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4049.withTypes to createDraftSafeSelector by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4080this in createSlice by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/4071tsconfig.typetests.json to include all TS files by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4091composeWithDevTools spy by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/4093Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.1...v2.1.0
Nothing published for this version
This major release revamps the build and publishing setup for the RTK Query OpenAPI Codegen, as well as merging _numerous_ PRs from external contribut
This major release revamps the build and publishing setup for the RTK Query OpenAPI Codegen, as well as merging numerous PRs from external contributors.
This should resolve many outstanding issues and feature requests.
There were no changes from 2.0.0-alpha.0.
This major release :
createSlice and createReducermiddleware and enhancers options of configureStore to require callbackscombineSlices method with support for lazy-loading slice reducerscreateSlice.reducers, with optional support for defining thunks inside of createSliceautoBatchEnhancer to configureStore by defaultThis release has breaking changes. (Note: v2.0.1 was released with a couple hotfixes for Reselect and Redux Thunk right as this was being finalized.)
This release is part of a wave of major versions of all the Redux packages: Redux Toolkit 2.0, Redux core 5.0, React-Redux 9.0, Reselect 5.0, and Redux Thunk 3.0.
For full details on all of the breaking changes and other significant changes to all of those packages, see the "Migrating to RTK 2.0 and Redux 5.0" migration guide in the Redux docs.
[!NOTE] The Redux core, Reselect, and Redux Thunk packages are included as part of Redux Toolkit, and RTK users do not need to manually upgrade them - you'll get them as part of the upgrade to RTK 2.0. (If you're not using Redux Toolkit yet, please start migrating your existing legacy Redux code to use Redux Toolkit today!)
# RTK
npm install @reduxjs/toolkit
yarn add @reduxjs/toolkit
createSlice.extraReducers and createReducer removedRTK's createReducer API was originally designed to accept a lookup table of action type strings to case reducers, like { "ADD_TODO": (state, action) => {} }. We later added the "builder callback" form to allow more flexibility in adding "matchers" and a default handler, and did the same for createSlice.extraReducers.
We have removed the "object" form for both createReducer and createSlice.extraReducers in RTK 2.0, as the builder callback form is effectively the same number of lines of code, and works much better with TypeScript.
As an example, this:
const todoAdded = createAction('todos/todoAdded')
createReducer(initialState, {
[todoAdded]: (state, action) => {},
})
createSlice({
name,
initialState,
reducers: {
/* case reducers here */
},
extraReducers: {
[todoAdded]: (state, action) => {},
},
})
should be migrated to:
createReducer(initialState, (builder) => {
builder.addCase(todoAdded, (state, action) => {})
})
createSlice({
name,
initialState,
reducers: {
/* case reducers here */
},
extraReducers: (builder) => {
builder.addCase(todoAdded, (state, action) => {})
},
})
To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax.
The codemods package is available on NPM as @reduxjs/rtk-codemods. More details are available here.
To run the codemods against your codebase, run npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js.
Examples:
npx @reduxjs/rtk-codemods createReducerBuilder ./src
npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts
We also recommend re-running Prettier on the codebase before committing the changes.
These codemods should work, but we would greatly appreciate feedback from more real-world codebases!
configureStore Options ChangesconfigureStore.middleware must be a callbackSince the beginning, configureStore has accepted a direct array value as the middleware option. However, providing an array directly prevents configureStore from calling getDefaultMiddleware(). So, middleware: [myMiddleware] means there is no thunk middleware added (or any of the dev-mode checks).
This is a footgun, and we've had numerous users accidentally do this and cause their apps to fail because the default middleware never got configured.
As a result, we've now made the middleware only accept the callback form. If for some reason you still want to replace all of the built-in middleware, do so by returning an array from the callback:
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) => {
// WARNING: this means that _none_ of the default middleware are added!
return [myMiddleware]
// or for TS users, use:
// return new Tuple(myMiddleware)
},
})
But note that we consistently recommend not replacing the default middleware entirely, and that you should use return getDefaultMiddleware().concat(myMiddleware).
configureStore.enhancers must be a callbackSimilarly to configureStore.middleware, the enhancers field must also be a callback, for the same reasons.
The callback will receive a getDefaultEnhancers function that can be used to customise the batching enhancer that's now included by default.
For example:
const store = configureStore({
reducer,
enhancers: (getDefaultEnhancers) => {
return getDefaultEnhancers({
autoBatch: { type: 'tick' },
}).concat(myEnhancer)
},
})
It's important to note that the result of getDefaultEnhancers will also contain the middleware enhancer created with any configured/default middleware. To help prevent mistakes, configureStore will log an error to console if middleware was provided and the middleware enhancer wasn't included in the callback result.
const store = configureStore({
reducer,
enhancers: (getDefaultEnhancers) => {
return [myEnhancer] // we've lost the middleware here
// instead:
return getDefaultEnhancers().concat(myEnhancer)
},
})
Also, note that if you supply the enhancers field, it must come after the middleware field in order for TS inference to work properly.
getDefaultMiddleware and getType removedThe standalone version of getDefaultMiddleware has been deprecated since v1.6.1, and has now been removed. Use the function passed to the middleware callback instead, which has the correct types.
We have also removed the getType export, which was used to extract a type string from action creators made with createAction. Instead, use the static property actionCreator.type.
We've had a number of reports where RTK Query had issues around usage of dispatch(endpoint.initiate(arg, {subscription: false})). There were also reports that multiple triggered lazy queries were resolving the promises at the wrong time. Both of these had the same underlying issue, which was that RTKQ wasn't tracking cache entries in these cases (intentionally). We've reworked the logic to always track cache entries (and remove them as needed), which should resolve those behavior issues.
We also have had issues raised about trying to run multiple mutations in a row and how tag invalidation behaves. RTKQ now has internal logic to delay tag invalidation briefly, to allow multiple invalidations to get handled together. This is controlled by a new invalidationBehavior: 'immediate' | 'delayed' flag on createApi. The new default behavior is 'delayed'. Set it to 'immediate' to revert to the behavior in RTK 1.9.
In RTK 1.9, we reworked RTK Query's internals to keep most of the subscription status inside the RTKQ middleware. The values are still synced to the Redux store state, but this is primarily for display by the Redux DevTools "RTK Query" panel. Related to the cache entry changes above, we've optimized how often those values get synced to the Redux state for perf.
The biggest theme of the Redux v5 and RTK 2.0 releases is trying to get "true" ESM package publishing compatibility in place, while still supporting CJS in the published package.
The primary build artifact is now an ESM file, dist/redux-toolkit.modern.mjs. Most build tools should pick this up. There's also a CJS artifact, and a second copy of the ESM file named redux-toolkit.legacy-esm.js to support Webpack 4 (which does not recognize the exports field in package.json). Additionally, all of the build artifacts now live under ./dist/ in the published package.
We now publish modern JS syntax targeting ES2020, including optional chaining, object spread, and other modern syntax. If you need to target older browsers, please transpile the packages yourself (or use the legacy-esm build artifact for ES2017).
We're now building the package using https://github.com/egoist/tsup. We also now include sourcemaps for the ESM and CJS artifacts.
Redux has always shipped with UMD build artifacts. These are primarily meant for direct import as script tags, such as in a CodePen or a no-bundler build environment.
We've dropped those build artifacts from the published package, on the grounds that the use cases seem pretty rare today.
There's now a redux-toolkit.browser.mjs file in the package that can be loaded from a CDN like Unpkg.
If you have strong use cases for us continuing to include UMD build artifacts, please let us know!
RTK now depends on Redux core 5.0, Reselect 5.0, and Redux Thunk 3.0. See the linked release notes for those libraries, as each of them has additional breaking changes. The "Migrating to RTK 2.0 and Redux 5.0" docs page also covers the combined changes in one page
RTK now also depends on Immer 10.0, which has several major improvements and updates:
We've also removed the prior call to automatically enable the Immer ES5 fallback mode any time RTK was loaded.
Redux 4.1.0 optimized its bundle size by extracting error message strings out of production builds, based on React's approach. We've applied the same technique to RTK. This saves about 1000 bytes from prod bundles (actual benefits will depend on which imports are being used).
We also noted that ESBuild does not deduplicate imports when it bundles source files, and this was causing RTK Query's bundle to contain a dozen references to import { } from "@reduxjs/toolkit", including some of the same methods. Manually deduplicating those saves about 600 bytes off the production RTKQ artifact.
reactHooksModule custom hook configurationPreviously, custom versions of React Redux's hooks (useSelector, useDispatch, and useStore) could be passed separately to reactHooksModule, usually to enable using a different context to the default ReactReduxContext.
In practicality, the react hooks module needs all three of these hooks to be provided, and it became an easy mistake to only pass useSelector and useDispatch, without useStore.
The module has now moved all three of these under the same configuration key, and will check that all three are provided if the key is present.
// previously
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
useStore: createStoreHook(MyContext),
})
)
// now
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
hooks: {
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
useStore: createStoreHook(MyContext),
},
})
)
Several other options were previously marked as deprecated, and have been removed. We've also removed polyfills like the AbortController polyfill.
configureStore field order for middleware mattersIf you are passing both the middleware and enhancers fields to configureStore, the middleware field must come first in order for internal TS inference to work properly.
TupleWe've seen many cases where users passing the middleware parameter to configureStore have tried spreading the array returned by getDefaultMiddleware(), or passed an alternate plain array. This unfortunately loses the exact TS types from the individual middleware, and often causes TS problems down the road (such as dispatch being typed as Dispatch<AnyAction> and not knowing about thunks).
getDefaultMiddleware() already used an internal MiddlewareArray class, an Array subclass that had strongly typed .concat/prepend() methods to correctly capture and retain the middleware types.
We've renamed that type to Tuple, and configureStore's TS types now require that you must use Tuple if you want to pass your own array of middleware:
import { configureStore, Tuple } from '@reduxjs/toolkit'
configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => new Tuple(additionalMiddleware, logger),
})
(Note that this has no effect if you're using RTK with plain JS, and you could still pass a plain array here.)
This same restriction applies to the enhancers field.
createEntityAdapter now has an Id generic argument, which will be used to strongly type the item IDs anywhere those are exposed. Previously, the ID field type was always string | number. TS will now try to infer the exact type from either the .id field of your entity type, or the selectId return type. You could also fall back to passing that generic type directly. If you use the EntityState<Data, Id> type directly, you must supply both generic arguments!
The .entities lookup table is now defined to use a standard TS Record<Id, MyEntityType>, which assumes that each item lookup exists by default. Previously, it used a Dictionary<MyEntityType> type, which assumed the result was MyEntityType | undefined. The Dictionary type has been removed.
If you prefer to assume that the lookups might be undefined, use TypeScript's noUncheckedIndexedAccess configuration option to control that.
These features are new in Redux Toolkit 2.0, and help cover additional use cases that we've seen users ask for in the ecosystem.
combineSlices API with slice reducer injection for code-splittingThe Redux core has always included combineReducers, which takes an object full of "slice reducer" functions and generates a reducer that calls those slice reducers. RTK's createSlice generates slice reducers + associated action creators, and we've taught the pattern of exporting individual action creators as named exports and the slice reducer as a default export. Meanwhile, we've never had official support for lazy-loading reducers, although we've had sample code for some "reducer injection" patterns in our docs.
This release includes a new combineSlices API that is designed to enable lazy-loading of reducers at runtime. It accepts individual slices or an object full of slices as arguments, and automatically calls combineReducers using the sliceObject.name field as the key for each state field. The generated reducer function has an additional .inject() method attached that can be used to dynamically inject additional slices at runtime. It also includes a .withLazyLoadedSlices() method that can be used to generate TS types for reducers that will be added later. See #2776 for the original discussion around this idea.
For now, we are not building this into configureStore, so you'll need to call const rootReducer = combineSlices(.....) yourself and pass that to configureStore({reducer: rootReducer}).
Basic usage: a mixture of slices and standalone reducers passed to combineSlices
const stringSlice = createSlice({
name: 'string',
initialState: '',
reducers: {},
})
const numberSlice = createSlice({
name: 'number',
initialState: 0,
reducers: {},
})
const booleanReducer = createReducer(false, () => {})
const api = createApi(/* */)
const combinedReducer = combineSlices(
stringSlice,
{
num: numberSlice.reducer,
boolean: booleanReducer,
},
api
)
expect(combinedReducer(undefined, dummyAction())).toEqual({
string: stringSlice.getInitialState(),
num: numberSlice.getInitialState(),
boolean: booleanReducer.getInitialState(),
api: api.reducer.getInitialState(),
})
Basic slice reducer injection
// Create a reducer with a TS type that knows `numberSlice` will be injected
const combinedReducer =
combineSlices(stringSlice).withLazyLoadedSlices<
WithSlice<typeof numberSlice>
>()
// `state.number` doesn't exist initially
expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)
// Create a version of the reducer with `numberSlice` injected (mainly useful for types)
const injectedReducer = combinedReducer.inject(numberSlice)
// `state.number` now exists, and injectedReducer's type no longer marks it as optional
expect(injectedReducer(undefined, dummyAction()).number).toBe(
numberSlice.getInitialState()
)
// original reducer has also been changed (type is still optional)
expect(combinedReducer(undefined, dummyAction()).number).toBe(
numberSlice.getInitialState()
)
selectors field in createSliceThe existing createSlice API now has support for defining selectors directly as part of the slice. By default, these will be generated with the assumption that the slice is mounted in the root state using slice.name as the field, such as name: "todos" -> rootState.todos. Additionally, there's now a slice.selectSlice method that does that default root state lookup.
You can call sliceObject.getSelectors(selectSliceState) to generate the selectors with an alternate location, similar to how entityAdapter.getSelectors() works.
const slice = createSlice({
name: 'counter',
initialState: 42,
reducers: {},
selectors: {
selectSlice: (state) => state,
selectMultiple: (state, multiplier: number) => state * multiplier,
},
})
// Basic usage
const testState = {
[slice.name]: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.selectors
expect(selectSlice(testState)).toBe(slice.getInitialState())
expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)
// Usage with the slice reducer mounted under a different key
const customState = {
number: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.getSelectors(
(state: typeof customState) => state.number
)
expect(selectSlice(customState)).toBe(slice.getInitialState())
expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)
createSlice.reducers callback syntax and thunk supportOne of the oldest feature requests we've had is the ability to declare thunks directly inside of createSlice. Until now, you've always had to declare them separately, give the thunk a string action prefix, and handle the actions via createSlice.extraReducers:
// Declare the thunk separately
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId: number, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
const usersSlice = createSlice({
name: 'users',
initialState,
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: (builder) => {
// Add reducers for additional action types here, and handle loading state as needed
builder.addCase(fetchUserById.fulfilled, (state, action) => {
state.entities.push(action.payload)
})
},
})
Many users have told us that this separation feels awkward.
We've wanted to include a way to define thunks directly inside of createSlice, and have played around with various prototypes. There were always two major blocking issues, and a secondary concern:
getState and dispatch, but the RootState and AppDispatch types are normally inferred from the store, which in turn infers it from the slice state types. Declaring thunks inside createSlice would cause circular type inference errors, as the store needs the slice types but the slice needs the store types. We weren't willing to ship an API that would work okay for our JS users but not for our TS users, especially since we want people to use TS with RTK.createAsyncThunk import optional. Either createSlice always depends on it (and adds that to the bundle size), or it can't use createAsyncThunk at all.We've settled on these compromises:
createSlice, you specifically need to set up a custom version of createSlice that has access to createAsyncThunk.createSlice.reducers, by using a "creator callback" syntax for the reducers field that is similar to the build callback syntax in RTK Query's createApi (using typed functions to create fields in an object). Doing this does look a bit different than the existing "object" syntax for the reducers field, but is still fairly similar.createSlice, but you cannot customize the state or dispatch types. If those are needed, you can manually do an as cast, like getState() as RootState.In practice, we hope these are reasonable tradeoffs. Creating thunks inside of createSlice has been widely asked for, so we think it's an API that will see usage. If the TS customization options are a limitation, you can still declare thunks outside of createSlice as always, and most async thunks don't need dispatch or getState - they just fetch data and return. And finally, setting up a custom createSlice allows you to opt into createAsyncThunk being included in your bundle size (though it may already be included if used directly or as part of RTK Query - in either of these cases there's no additional bundle size).
Here's what the new callback syntax looks like:
const createSliceWithThunks = buildCreateSlice({
creators: { asyncThunk: asyncThunkCreator },
})
const todosSlice = createSliceWithThunks({
name: 'todos',
initialState: {
loading: false,
todos: [],
error: null,
} as TodoState,
reducers: (create) => ({
// A normal "case reducer", same as always
deleteTodo: create.reducer((state, action: PayloadAction<number>) => {
state.todos.splice(action.payload, 1)
}),
// A case reducer with a "prepare callback" to customize the action
addTodo: create.preparedReducer(
(text: string) => {
const id = nanoid()
return { payload: { id, text } }
},
// action type is inferred from prepare callback
(state, action) => {
state.todos.push(action.payload)
}
),
// An async thunk
fetchTodo: create.asyncThunk(
// Async payload function as the first argument
async (id: string, thunkApi) => {
const res = await fetch(`myApi/todos?id=${id}`)
return (await res.json()) as Item
},
// An object containing `{pending?, rejected?, fulfilled?, settled?, options?}` second
{
pending: (state) => {
state.loading = true
},
rejected: (state, action) => {
state.error = action.payload ?? action.error
},
fulfilled: (state, action) => {
state.todos.push(action.payload)
},
// settled is called for both rejected and fulfilled actions
settled: (state, action) => {
state.loading = false
},
}
),
}),
})
// `addTodo` and `deleteTodo` are normal action creators.
// `fetchTodo` is the async thunk
export const { addTodo, deleteTodo, fetchTodo } = todosSlice.actions
Using the new callback syntax is entirely optional (the object syntax is still standard), but an existing slice would need to be converted before it can take advantage of the new capabilities this syntax provides. To make this easier, a codemod is provided.
npx @reduxjs/rtk-codemods createSliceReducerBuilder ./src/features/todos/slice.ts
A Redux store's middleware pipeline is fixed at store creation time and can't be changed later. We have seen ecosystem libraries that tried to allow dynamically adding and removing middleware, potentially useful for things like code splitting.
This is a relatively niche use case, but we've built our own version of a "dynamic middleware" middleware. Add it to the Redux store at setup time, and it lets you add middleware later at runtime. It also comes with a React hook integration that will automatically add a middleware to the store and return the updated dispatch method..
import { createDynamicMiddleware, configureStore } from '@reduxjs/toolkit'
const dynamicMiddleware = createDynamicMiddleware()
const store = configureStore({
reducer: {
todos: todosReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(dynamicMiddleware.middleware),
})
// later
dynamicMiddleware.addMiddleware(someOtherMiddleware)
configureStore adds autoBatchEnhancer by defaultIn v1.9.0, we added a new autoBatchEnhancer that delays notifying subscribers briefly when multiple "low-priority" actions are dispatched in a row. This improves perf, as UI updates are typically the most expensive part of the update process. RTK Query marks most of its own internal actions as "low-pri" by default, but you have to have the autoBatchEnhancer added to the store to benefit from that.
We've updated configureStore to add the autoBatchEnhancer to the store setup by default, so that users can benefit from the improved perf without needing to manually tweak the store config themselves.
entityAdapter.getSelectors accepts a createSelector functionentityAdapter.getSelectors() now accepts an options object as its second argument. This allows you to pass in your own preferred createSelector method, which will be used to memoize the generated selectors. This could be useful if you want to use one of Reselect's new alternate memoizers, or some other memoization library with an equivalent signature.
We now have a docs page that covers how to set up Redux properly with Next.js. We've seen a lot of questions around using Redux, Next, and the App Router together, and this guide should help provide advice.
(At this time, the Next.js with-redux example is still showing outdated patterns - we're going to file a PR shortly to update that to match our docs guide.)
v2.0-integration by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3253arethetypeswrong automated CLI check by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3294attw CLI option to treat problems as non-errors by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3316tsup by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3362responseHandler being used in fetchBaseQuery by @praxxis in https://github.com/reduxjs/redux-toolkit/pull/3137resetApiState by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/3333subscriptionUpdated as autobatched by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3364createSelector instance to adapter.getSelectors by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/3481listenerApi.throwIfCancelled() by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3802autotrackMemoize by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3831createDraftSafeSelector. by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/3722Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.3...v2.0.0
…for an overview of breaking changes in RTK 2.0 and Redux core.
This release candidate updates to the latest Reselect 5.0 RC to pick up the rename of defaultMemoize to lruMemoize.
Note that we hope to release Redux Toolkit 2.0, Redux core 5.0, and React-Redux 9.0 by this weekend!
See the preview Redux Toolkit 2.0 + Redux core 5.0 Migration Guide for an overview of breaking changes in RTK 2.0 and Redux core.
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
npm install @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
The previous v2.0.0-rc.2 release picked up Reselect's dev mode checks for result functions that just return their input, like x => x. Turns out that some of RTK Query's internal selector usage did that in some cases :) That resulted in a ton of warnings being printed. We've updated our internals to fix that.
The Reselect defaultMemoize function has now been renamed to lruMemoize, since it's no longer the default. See the Reselect v5.0.0-rc.1 release notes for more details.
lruMemoize rename by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3933Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-rc.2...v2.0.0-rc.3
…for an overview of breaking changes in RTK 2.0 and Redux core.
This release candidate updates to the latest Reselect 5.0 RC to pick up the change to use weakMapMemoize as the default inside createSelector.
Note that we hope to release Redux Toolkit 2.0, Redux core 5.0, and React-Redux 9.0 by the start of December! (If we don't hit that, we'll aim for January, after the holidays.)
See the preview Redux Toolkit 2.0 + Redux core 5.0 Migration Guide for an overview of breaking changes in RTK 2.0 and Redux core.
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
npm install @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
Reselect v5.0.0-rc.0 makes the breaking change to use weakMapMemoize as the default memoization implementation for createSelector. This memoizer has an effectively infinite cache size, which should cut down on the number of recalculations in a typical app, and help improve performance overall. This is a breaking change, but one that should be invisible to most users.
It also adds a new dev-mode check for result functions that look like x => x, which is almost always a mistake.
See the Reselect v5.0.0-rc.0 release notes for more details.
weakMapMemoize change by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3928Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-rc.1...v2.0.0-rc.2
…for an overview of breaking changes in RTK 2.0 and Redux core.
This release candidate updates to the latest Redux 5.0 RC to use its exported isAction and isPlainObject util methods, renames the pre-minified ESM production build to redux-toolkit.browser.mjs and drops the ESM precompiled dev build, and updates build tooling.
Note that we hope to release Redux Toolkit 2.0, Redux core 5.0, and React-Redux 9.0 by the start of December! (If we don't hit that, we'll aim for January, after the holidays.)
See the preview Redux Toolkit 2.0 + Redux core 5.0 Migration Guide for an overview of breaking changes in RTK 2.0 and Redux core.
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
npm install @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
isAction PredicateWe recently added an isAction predicate to RTK, then realized it's better suited for the Redux core. This can be used anywhere you have a value that could be a Redux action object, and you need to check if it is actually an action. This is specifically useful for use with the updated Redux middleware TS types, where the default value is now unknown and you need to use a type guard to tell TS that the current value is actually an action.
This is now exported from the Redux core, and re-exported from RTK, which also uses it internally to avoid duplicating that logic.
We've also exported the isPlainObject util that's been in the Redux codebase for years as well.
We previously dropped the UMD build artifacts in an earlier alpha, but added ESM build artifacts that are pre-compiled to remove the process.env.NODE_ENV definitions, with the intent that these are useable as <script type="module"> tags in the browser. Those were previously named as redux-toolkit.modern.development.mjs and redux-toolkit.modern.production.mjs.
We've renamed the production artifact to redux-toolkit.browser.mjs to be consistent with the other Redux-related packages, and removed the dev build artifact on the grounds that we don't think there's enough likely usage to include it. If you think you would specifically benefit from having an ESM browser-compatible dev artifact, let us know!
v2.0-integration by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3903Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-rc.0...v2.0.0-rc.1
…for an overview of breaking changes in RTK 2.0 and Redux core.
This release candidate modifies the approach for defining async thunks inside of createSlice, and improves several bits of usage and implementation around selectors.
Note that we hope to release Redux Toolkit 2.0, Redux core 5.0, and React-Redux 9.0 by the start of December! (If we don't hit that, we'll aim for January, after the holidays.)
See the preview Redux Toolkit 2.0 + Redux core 5.0 Migration Guide for an overview of breaking changes in RTK 2.0 and Redux core.
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
npm install @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
createSlice changesIn earlier alphas, we added the ability to define async thunks directly inside of createSlice.reducers, using a callback syntax. However, that meant that createSlice had a hard dependency on createAsyncThunk, and importing createSlice would always include createAsyncThunk in an app bundle even if it wasn't being used.
In practice, we expect that most RTK users will use createAsyncThunk, either directly or as part of RTK Query. But, we take bundle size seriously, and didn't want to force all uses of createSlice to add the 2K for createAsyncThunk to a bundle if it isn't actually being used.
Since we expect that defining thunks inside of createSlice is a less-common use case, we've settled on a compromise. The standard createSlice method does not support calling create.asyncThunk() inside even if you use the callback syntax. Instead, you need to call buildCreateSlice() to create a customized version of createSlice with the async thunk capabilities built in, and use that:
const createSliceWithThunks = buildCreateSlice({
creators: { asyncThunk: asyncThunkCreator },
})
const todosSlice = createSliceWithThunks ({
name: 'todos',
initialState: {
loading: false,
todos: [],
error: null,
} as TodoState,
reducers: (create) => ({
// A normal "case reducer", same as always
deleteTodo: create.reducer((state, action: PayloadAction<number>) => {
state.todos.splice(action.payload, 1)
}),
// A case reducer with a "prepare callback" to customize the action
addTodo: create.preparedReducer(
(text: string) => {
const id = nanoid()
return { payload: { id, text } }
},
// action type is inferred from prepare callback
(state, action) => {
state.todos.push(action.payload)
}
),
// An async thunk
fetchTodo: create.asyncThunk(
// Async payload function as the first argument
async (id: string, thunkApi) => {
const res = await fetch(`myApi/todos?id=${id}`)
return (await res.json()) as Item
},
// An object containing `{pending?, rejected?, fulfilled?, settled?, options?}` second
{
pending: (state) => {
state.loading = true
},
rejected: (state, action) => {
state.error = action.payload ?? action.error
},
fulfilled: (state, action) => {
state.todos.push(action.payload)
},
// settled is called for both rejected and fulfilled actions
settled: (state, action) => {
state.loading = false
},
}
),
}),
})
createSlice now adds a selectSlice field to all slice objects. This simple selector assumes that the slice has been added at rootState[slice.name] (or rootState[slice.reducerPath] if defined). This is useful for basic lookups of the slice's state.
entityAdapter.getSelectors() now accepts alternate selector creators with customized memoization options.
createDraftSafeSelector. by @aryaemami59 in https://github.com/reduxjs/redux-toolkit/pull/3722Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-beta.4...v2.0.0-rc.0
This beta release updates RTK Query to fix issues around cache entry behavior when subscription: false is used or with multiple lazy queries in progre
This beta release updates RTK Query to fix issues around cache entry behavior when subscription: false is used or with multiple lazy queries in progress, alters RTK Query's tag invalidation behavior to better handle cases where multiple invalidations may happen in sequence, rewrites RTK Query's internals to improve performance around subscription data syncing, and updates Reselect to the latest 5.0.0-beta.0.
npm i @reduxjs/toolkit@beta
yarn add @reduxjs/toolkit@beta
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
We've had a number of reports where RTK Query had issues around usage of dispatch(endpoint.initiate(arg, {subscription: false})). There were also reports that multiple triggered lazy queries were resolving the promises at the wrong time. Both of these had the same underlying issue, which was that RTKQ wasn't tracking cache entries in these cases (intentionally). We've reworked the logic to always track cache entries (and remove them as needed), which should resolve those behavior issues.
We also have had issues raised about trying to run multiple mutations in a row and how tag invalidation behaves. RTKQ now has internal logic to delay tag invalidation briefly, to allow multiple invalidations to get handled together. This is controlled by a new invalidationBehavior: 'immediate' | 'delayed' flag on createApi. The new default behavior is 'delayed'. Set it to 'immediate' to revert to the behavior in RTK 1.9.
In RTK 1.9, we reworked RTK Query's internals to keep most of the subscription status inside the RTKQ middleware. The values are still synced to the Redux store state, but this is primarily for display by the Redux DevTools "RTK Query" panel. Related to the cache entry changes above, we've optimized how often those values get synced to the Redux state for perf.
We've updated the Reselect dependency to Reselect 5.0.0-beta.0, which adds the ability to pass memoizer functions and options directly to createSelector.
The new create.asyncThunk() builder inside of createSlice can now be given a settled reducer, which will run when the thunk promise either fulfills or rejects.
autotrackMemoize by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3831Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-beta.3...v2.0.0-beta.4
This beta release updates configureStore to remove the deprecated option of passing an array for middleware, improves the createEntityAdapter types to…
This beta release updates configureStore to remove the deprecated option of passing an array for middleware, improves the createEntityAdapter types to improve compatibility, updates deps to use the latest React-Redux beta, and optimizes the TS compile perf for RTKQ hooks.
npm i @reduxjs/toolkit@beta
yarn add @reduxjs/toolkit@beta
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
configureStore.middleware Option Must Be A CallbackSince the beginning, configureStore has accepted a direct array value as the middleware option. However, providing an array directly prevents configureStore from calling getDefaultMiddleware(). So, middleware: [myMiddleware]` means there is no thunk middleware added (or any of the dev-mode checks).
This is a footgun, and we've had numerous users accidentally do this and cause their apps to fail because the default middleware never got configured.
We already had made the enhancers option only accept the callback form, so we've done the same thing for middleware.
If for some reason you still want to replace all of the built-in middleware, do so by returning an array from the callback:
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) => {
// WARNING: this means that _none_ of the default middleware are added!
return [myMiddleware];
// or for correct TS inference, use:
// return new Tuple(myMiddleware)
}
})
But note that we consistently recommend not replacing the default middleware entirely, and that you should use return getDefaultMiddleware().concat(myMiddleware).
The types for createEntityAdapter have been reworked for better compat with Immer drafts.
The RTK Query types for generating React hooks have been optimized for much faster TS compilation perf (~60% improvement in one synthetic example app).
RTK Query's custom React hooks option now checks at runtime that all 3 hooks have been provided.
A new codemod is now available as part of the @reduxjs/rtk-codemods package that will convert a given createSlice call to the new "create callback" notation, which is primarily used for adding thunks inside of createSlice. Unlike the other codemods for replacing the obsolete/removed object syntax in createReducer and createSlice, this is purely optional.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-beta.2...v2.0.0-beta.3
This beta release updates the build step to extract error messages and optimizes internal imports in RTK Query for smaller production bundle sizes, ad
This beta release updates the build step to extract error messages and optimizes internal imports in RTK Query for smaller production bundle sizes, adds a selectCachedArgsForQuery util, and includes all changes in v1.9.6
npm i @reduxjs/toolkit@beta
yarn add @reduxjs/toolkit@beta
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
Redux 4.1.0 optimized its bundle size by extracting error message strings out of production builds, based on React's approach. We've applied the same technique to RTK. This saves about 1000 bytes from prod bundles (actual benefits will depend on which imports are being used).
We also noted that ESBuild does not deduplicate imports when it bundles source files, and this was causing RTK Query's bundle to contain a dozen references to import { } from "@reduxjs/toolkit", including some of the same methods. Manually deduplicating those saves about 600 bytes off the production RTKQ artifact.
We've added a selectCachedArgsForQuery util selector that will return the saved arguments that were used for a given cache entry.
This also includes all of the changes in v1.9.6.
1.9.6 into v2.0-integration by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3743Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-beta.1...v2.0.0-beta.2
This beta release updates the build and packaging setup to improve TS and ESM compatibility, fixes several TS issues, and updates to the latest React-
This beta release updates the build and packaging setup to improve TS and ESM compatibility, fixes several TS issues, and updates to the latest React-Redux and Redux-Thunk deps.
npm i @reduxjs/toolkit@beta
yarn add @reduxjs/toolkit@beta
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
We've made several tweaks to the packaging to improve compatibility for ESM and TS typedef definitions, which should fix some issues that were reported with beta.0.
We also fixed several assorted TS issues that were affecting users in specific edge cases.
We removed the AbortController polyfill from createAsyncThunk, saving some bytes.
We've updated deps to redux-thunk@3.0.0-beta.0 and react-redux@9.0.0-alpha.0.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-beta.0...v2.0.0-beta.1
…changes from the 2.0 alphas. This release has breaking changes.
This beta release updates many of our TS types for improved type safety and behavior, updates entityAdapter.getSelectors() to accept a createSelector option, depends on the latest redux@5.0-beta.0 release, and includes all prior changes from the 2.0 alphas. This release has breaking changes.
npm i @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for most of the new features here:
We've seen many cases where users passing the middleware parameter to configureStore have tried spreading the array returned by getDefaultMiddleware(), or passed an alternate plain array. This unfortunately loses the exact TS types from the individual middleware, and often causes TS problems down the road (such as dispatch being typed as Dispatch<AnyAction> and not knowing about thunks).
getDefaultMiddleware() already used an internal MiddlewareArray class, an Array subclass that had strongly typed .concat/prepend() methods to correctly capture and retain the middleware types.
We've renamed that type to Tuple, and configureStore's TS types now require that you must use Tuple if you want to pass your own array of middleware:
import { configureStore, Tuple } from '@reduxjs/toolkit'
configureStore({
reducer: rootReducer,
middleware: new Tuple(additionalMiddleware, logger),
})
(Note that this has no effect if you're using RTK with plain JS, and you could still pass a plain array here.)
Similarly, the enhancers field used to accept an array directly. It now is a callback that receives a getDefaultEnhancers method, equivalent to getDefaultMiddleware():
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
enhancers: (getDefaultEnhancers) =>
getDefaultEnhancers({
autoBatch: false,
}).concat(batchedSubscribe(debounceNotify)),
})
It too expects a Tuple return value if you're using TS.
entityAdapter.getSelectors() now accepts an options object as its second argument. This allows you to pass in your own preferred createSelector method, which will be used to memoize the generated selectors. This could be useful if you want to use one of Reselect's new alternate memoizers, or some other memoization library with an equivalent signature.
createEntityAdapter now has an Id generic argument, which will be used to strongly type the item IDs anywhere those are exposed. Previously, the ID field type was always string | number. TS will now try to infer the exact type from either the .id field of your entity type, or the selectId return type. You could also fall back to passing that generic type directly.
The .entities lookup table is now defined to use a standard TS Record<Id, MyEntityType>, which assumes that each item lookup exists by default. Previously, it used a Dictionary<MyEntityType> type, which assumed the result was MyEntityType | undefined. The Dictionary type has been removed.
If you prefer to assume that the lookups might be undefined, use TypeScript's noUncheckedIndexedAccess configuration option to control that.
UnknownAction TypeThe Redux core TS types have always exported an AnyAction type, which is defined to have {type: string} and treat any other field as any. This makes it easy to write uses like console.log(action.whatever), but unfortunately does not provide any meaningful type safety.
We now export an UnknownAction type, which treats all fields other than action.type as unknown. This encourages users to write type guards that check the action object and assert its specific TS type. Inside of those checks, you can access a field with better type safety.
UnknownAction is now the default any place in the Redux and RTK source that expects an action object.
AnyAction still exists for compatibility, but has been marked as deprecated.
Note that Redux Toolkit's action creators have a .match() method that acts as a useful type guard:
if (todoAdded.match(someUnknownAction)) {
// action is now typed as a PayloadAction<Todo>
}
Summarizing the changes from earlier alphas:
combineSlices API with built-in support for slice reducer injection for code-splittingselectors field in createSlicecreateSlice.reducers, which allows defining thunks inside createSliceconfigureStore adds autoBatchEnhancer by defaultautotrack and weakmap memoizers with different tradeoffscreateReducer and createSlice.extraReducers has been removed5.0-betaactionCreator.toString() override removed (although we're reconsidering this)getDefaultMiddleware removedcreateSelector instance to adapter.getSelectors by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/3481Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.6...v2.0.0-beta.0
This is an alpha release for Redux Toolkit 2.0, and has breaking changes. This release updates createSlice to allow declaring thunks directly inside t…
This is an alpha release for Redux Toolkit 2.0, and has breaking changes. This release updates createSlice to allow declaring thunks directly inside the reducers field using a callback syntax, adds a new "dynamic middleware" middleware, updates configureStore to add the autoBatchEnhancer by default, removes the .toString() override from action creators, updates Reselect from v4.x to v5.0-alpha, updates the Redux core to v5.0-alpha.6, and includes the latest changes from 1.9.x.
npm i @reduxjs/toolkit@alpha
yarn add @reduxjs/toolkit@alpha
The 2.0 integration branch contains the docs preview for the 2.0 changes. Not all changes are documented yet, but you can see API reference pages for some of the new features here:
createSlice.reducersOne of the oldest feature requests we've had is the ability to declare thunks directly inside of createSlice. Until now, you've always had to declare them separately, give the thunk a string action prefix, and handle the actions via createSlice.extraReducers:
// Declare the thunk separately
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId: number, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
const usersSlice = createSlice({
name: 'users',
initialState,
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: (builder) => {
// Add reducers for additional action types here, and handle loading state as needed
builder.addCase(fetchUserById.fulfilled, (state, action) => {
state.entities.push(action.payload)
})
},
})
Many users have told us that this separation feels awkward.
We've wanted to include a way to define thunks directly inside of createSlice, and have played around with various prototypes. There were always two major blocking issues, and a secondary concern:
1 It wasn't clear what the syntax for declaring a thunk inside should look like.
2. Thunks have access to getState and dispatch, but the RootState and AppDispatch types are normally inferred from the store, which in turn infers it from the slice state types. Declaring thunks inside createSlice would cause circular type inference errors, as the store needs the slice types but the slice needs the store types. We weren't willing to ship an API that would work okay for our JS users but not for our TS users, especially since we want people to use TS with RTK.
3. You can't do synchronous conditional imports in ES modules, and there's no good way to make the createAsyncThunk import optional. Either createSlice always depends on it (and adds that to the bundle size), or it can't use createAsyncThunk at all.
We've settled on these compromises:
createSlice.reducers, by using a "creator callback" syntax for the reducers field that is similar to the build callback syntax in RTK Query's createApi (using typed functions to create fields in an object). Doing this does look a bit different than the existing "object" syntax for the reducers field, but is still fairly similar.createSlice, but you cannot customize the state or dispatch types. If those are needed, you can manually do an as cast, like getState() as RootState.createSlice does now always depend on createAsyncThunk, so the createAsyncThunk implementation will get added to the bundle.In practice, we hope these are reasonable tradeoffs. Creating thunks inside of createSlice has been widely asked for, so we think it's an API that will see usage. If the TS customization options are a limitation, you can still declare thunks outside of createSlice as always, and most async thunks don't need dispatch or getState - they just fetch data and return. And finally, createAsyncThunk is already being used in many apps, either directly or as part of RTK Query, so in that case there's no additional bundle size increase - you've already paid that cost.
Here's what the new callback syntax looks like:
const todosSlice = createSlice({
name: 'todos',
initialState: {
loading: false,
todos: [],
} as TodoState,
reducers: (create) => ({
// A normal "case reducer", same as always
deleteTodo: create.reducer((state, action: PayloadAction<number>) => {
state.todos.splice(action.payload, 1)
}),
// A case reducer with a "prepare callback" to customize the action
addTodo: create.preparedReducer(
(text: string) => {
const id = nanoid()
return { payload: { id, text } }
},
// action type is inferred from prepare callback
(state, action) => {
state.todos.push(action.payload)
}
),
// An async thunk
fetchTodo: create.asyncThunk(
// Async payload function as the first argument
async (id: string, thunkApi) => {
const res = await fetch(`myApi/todos?id=${id}`)
return (await res.json()) as Item
},
// An object containing `{pending?, rejected?, fulfilled?, options?}` second
{
pending: (state) => {
state.loading = true
},
rejected: (state, action) => {
state.loading = false
},
fulfilled: (state, action) => {
state.loading = false
state.todos.push(action.payload)
},
}
),
}),
})
// `addTodo` and `deleteTodo` are normal action creators.
// `fetchTodo` is the async thunk
export const { addTodo, deleteTodo, fetchTodo } = todosSlice.actions
A Redux store's middleware pipeline is fixed at store creation time and can't be changed later. We have seen ecosystem libraries that tried to allow dynamically adding and removing middleware, potentially useful for things like code splitting.
This is a relatively niche use case, but we've built our own version of a "dynamic middleware" middleware. Add it to the Redux store at setup time, and it lets you add and remove middleware later at runtime. It also comes with a React hook integration that will automatically add a middleware to the store and return the updated dispatch method.
import { createDynamicMiddleware, configureStore } from '@reduxjs/toolkit'
const dynamicMiddleware = createDynamicMiddleware()
const store = configureStore({
reducer: {
todos: todosReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(dynamicMiddleware.middleware),
})
// later
dynamicMiddleware.addMiddleware(someOtherMiddleware)
autoBatchEnhancer By DefaultIn v1.9.0, we added a new autoBatchEnhancer that delays notifying subscribers briefly when multiple "low-priority" actions are dispatched in a row. This improves perf, as UI updates are typically the most expensive part of the update process. RTK Query marks most of its own internal actions as "low-pri" by default, but you have to have the autoBatchEnhancer added to the store to benefit from that.
We've updated configureStore to add the autoBatchEnhancer to the store setup by default, so that users can benefit from the improved perf without needing to manually tweak the store config themselves.
configureStore now also accepts a callback for the enhancers option that receives a getDefaultEnhancers() param, equivalent to how the middleware callback receives getDefaultMiddleware():
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(loggerMiddleware),
preloadedState,
enhancers: (getDefaultEnhancers) =>
getDefaultEnhancers().concat(anotherEnhancer),
})
When we first released the early alphas of RTK, one of the main selling points was that you could reuse RTK's action creators as "computed key" fields in the object argument to createReducer, like:
const todoAdded = createAction("todos/todoAdded");
const reducer = createReducer([], {
[todoAdded]: (state, action) => {}
})
This was possible because createAction overrides the fn.toString() field on these action creators to return the action type string. When JS sees the function, it implicitly calls todoAdded.toString(), which returns "todos/todoAdded", and that string is used as the key.
While this capability was useful early on, it's not useful today. Most users never call createAction, because createSlice automatically generates action creators. Additionally, it has no TS type safety. TS only sees that the key is a string, and has no idea what the correct TS type for action is. We later created the "builder callback" syntax for both createReducer and createSlice.extraReducers, started teaching that as the default, and removed the "object" argument to both of those in an earlier RTK 2.0 alpha.
Because of this, we've now removed the fn.toString() override. If you need to access the type string from an action creator function, those still have a .type field attached:
const todoAdded = createAction("todos/todoAdded");
console.log(todoAdded.type) // "todos/todoAdded"
We've also removed the standalone export of getDefaultMiddleware, which has been deprecated ever since we added the callback for the configureStore.middleware field that has correct types attached.
Finally, we've removed all other fields or type exports that were marked as deprecated in 1.9.x.
We've updated Reselect with the same ESM/CJS package formatting updates as the rest of the Redux libraries.
Reselect v5 alpha now includes a pair of new memoizers: autotrackMemoize, which uses signal-style field tracking, and weakmapMemoize, which has an effectively infinite cache size thanks to use of WeakMaps for tracking arguments.
We'd appreciate it if users would try out the new memoizers in their apps and give us feedback on their usefulness and any problems or suggestions!
You can use these by creating a customized version of createSelector, and RTK now exports createSelectorCreator and all three memoizers:
import { createSelectorCreator, autotrackMemoize} from "@reduxjs/toolkit"
const createSelectorAutotrack = createSelectorCreator(autotrackMemoize);
See the Reselect v5 alpha release notes for details on the tradeoffs with each memoizer:
Reselect also now automatically calls each selector twice on first execution in development builds, in order to detect cases where input selectors accidentally return new references too often (which would cause memoization to fail):
This can be configured on a per-selector basis. There's also a global setInputStabilityCheckEnabled() override method that is exported from the reselect package, but is not re-exported from RTK, as we think the check-once behavior is the right default. If you really want to override that globally, add reselect as an explicit dependency and import the override from there.
We've updated to Redux core v2.0-alpha.6, which enforces that action.type must be a string. In practice this shouldn't affect any of our users - action type strings are mostly an implementation detail now, and RTK uses strings for all actions.
We've updated all the Redux libraries to requires TS 4.7 as a minimum version. Some of our new types require this anyway, and it also simplifies the maintenance of our type definitions.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.5...v2.0.0-alpha.6
…includes the latest changes from 1.9.x, and has breaking changes.
This is an alpha release for Redux Toolkit 2.0. This release adds a new combineSlices API for reducer injection, has many changes to our build setup and published package contents, updates the redux dep to the latest alpha, updates the immer dep to 10.0 final, includes the latest changes from 1.9.x, and has breaking changes.
combineSlices APIThe Redux core has always included combineReducers, which takes an object full of "slice reducer" functions and generates a reducer that calls those slice reducers. RTK's createSlice generates slice reducers + associated action creators, and we've taught the pattern of exporting individual action creators as named exports and the slice reducer as a default export. Meanwhile, we've never had official support for lazy-loading reducers, although we've had sample code for some "reducer injection" patterns in our docs.
This release includes a new combineSlices API that is designed to enable lazy-loading of reducers at runtime. It accepts individual slices or an object full of slices as arguments, and automatically calls combineReducers using the sliceObject.name field as the key for each state field. The generated reducer function has an additional .inject() method attached that can be used to dynamically inject additional slices at runtime. It also includes a .withLazyLoadedSlices() method that can be used to generate TS types for reducers that will be added later. See https://github.com/reduxjs/redux-toolkit/issues/2776 for the original discussion around this idea.
For now, we are not building this into configureStore, so you'll need to call const rootReducer = combineSlices(.....) yourself and pass that to configureStore({reducer: rootReducer}).
We don't have documentation added for these features yet, but here's example usages from the combineSlices PR tests:
combineSlices
const stringSlice = createSlice({
name: 'string',
initialState: '',
reducers: {},
})
const numberSlice = createSlice({
name: 'number',
initialState: 0,
reducers: {},
})
const booleanReducer = createReducer(false, () => {})
const api = createApi(/* */)
const combinedReducer = combineSlices(
stringSlice,
{
num: numberSlice.reducer,
boolean: booleanReducer,
},
api
)
expect(combinedReducer(undefined, dummyAction())).toEqual({
string: stringSlice.getInitialState(),
num: numberSlice.getInitialState(),
boolean: booleanReducer.getInitialState(),
api: api.reducer.getInitialState(),
})
// Create a reducer with a TS type that knows `numberSlice` will be injected
const combinedReducer =
combineSlices(stringSlice).withLazyLoadedSlices<
WithSlice<typeof numberSlice>
>()
// `state.number` doesn't exist initially
expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)
// Create a new reducer with `numberSlice` injected
const injectedReducer = combinedReducer.inject(numberSlice)
// `state.number` now exists
expect(injectedReducer(undefined, dummyAction()).number).toBe(
numberSlice.getInitialState()
)
createSliceThe existing createSlice API now has support for defining selectors directly as part of the slice. By default, these will be generated with the assumption that the slice is mounted in the root state using slice.name as the field, such as name: "todos" -> rootState.todos. You can call sliceObject.getSelectors(selectSliceState) to generate the selectors with an alternate location, similar to how entityAdapter.getSelectors() works.
const slice = createSlice({
name: 'counter',
initialState: 42,
reducers: {},
selectors: {
selectSlice: (state) => state,
selectMultiple: (state, multiplier: number) => state * multiplier,
},
})
// Basic usage
const testState = {
[slice.name]: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.selectors
expect(selectSlice(testState)).toBe(slice.getInitialState())
expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)
// Usage with the slice reducer mounted under a different key
const customState = {
number: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.getSelectors(
(state: typeof customState) => state.number
)
expect(selectSlice(customState)).toBe(slice.getInitialState())
expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)
We've switched our build setup to use tsup, an ESBuild-powered build framework. This release should have identical build artifacts to 2.0.0-alpha.4, but let us know if there are any issues!
Immer 10.0 is now final, and has several major improvements and updates:
We've updated RTK to depend on the final Immer 10.0 release .
We've updated RTK to use the latest Redux 5.0-alpha.5 release, which tweaks the Reducer type, drops the internal $CombinedState type, and updates middleware types to default to unknown for actions.
For RTK, we've improved type inference for store enhancers, especially those that add additional fields to the state or store.
tsup by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3362responseHandler being used in fetchBaseQuery by @praxxis in https://github.com/reduxjs/redux-toolkit/pull/3137resetApiState by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/3333subscriptionUpdated as autobatched by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3364Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.4...v2.0.0-alpha.5
…the immer dep to the latest 10.x beta, and has breaking changes.
This is an alpha release for Redux Toolkit 2.0. This release has many changes to our build setup and published package contents, updates the redux and redux-thunk deps to the latest alphas, updates the immer dep to the latest 10.x beta, and has breaking changes.
npm i @reduxjs/toolkit@alpha
yarn add @reduxjs/toolkit@alpha
Also see the redux@5.0.0-alpha.4 release notes.
The biggest theme of the Redux v5 and RTK 2.0 releases is trying to get "true" ESM package publishing compatibility in place, while still supporting CJS in the published package.
Earlier alphas made changes to the package.json contents and published build artifacts in an attempt to get ESM+CJS compat working correctly, but those alphas had several varying compat issues.
We've set up a battery of example applications in the RTK repo that use a variety of build tools (currently CRA4, CRA5, Next 13, and Vite, Node CJS mode, and Node ESM mode), to verify that Redux and Redux Toolkit compile, import, and run correctly with both TS and various bundlers. We've also set up a check using a custom CLI wrapper around https://arethetypeswrong.github.io to check for potential packaging incompatibilities.
This release changes the names and contents of the published build artifacts, and the various exports/module/main fields in package.json to point to those.
We already tried to point to ESM build artifacts as the default. That should hopefully be be more consistent now.
As of this release, we think we have ESM+CJS compat working correctly, but we ask that the community try out the alphas in your apps and let us know of any compat problems!
Note: The one known potential issue is that TypeScript's new
moduleResolution: "node16"mode may see a mismatch between the ESM artifacts and the TS typedefs when imported in a Node CJS environment, and [that may allow hypothetically-incorrect import usage. (See ongoing discussion in https://github.com/arethetypeswrong/arethetypeswrong.github.io/issues/21 .) In practice, we think that probably won't be a concern, and we'll do further investigation before a final release.
Redux has always shipped with UMD build artifacts. These are primarily meant for direct import as script tags, such as in a CodePen or a no-bundler build environment.
For now, we're dropping those build artifacts from the published package, on the grounds that the use cases seem pretty rare today.
We do have browser-ready ESM build artifacts included, which already have process.env.NODE_ENV compiled away for either development or production behavior. These can be loaded via a script tag that points to that file on Unpkg.
If you have strong use cases for us continuing to include UMD build artifacts, please let us know!
Immer 10 is now in beta. It has several major changes, including faster perf, dropping ES5 environment support, and switching from a default export to only named exports.
We've updated RTK to depend on immer@10.0.0-beta.4.
Performance testing in an artificial RTKQ stress test project showed significant perf increases when dealing with many RTKQ-connected components loading, and that was directly due to Immer-powered reducers executing much faster.
While reducers are not usually the bottleneck in React+Redux apps, this looks like it will be a very nice improvement!
arethetypeswrong automated CLI check by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3294attw CLI option to treat problems as non-errors by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3316Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.2...v2.0.0-alpha.4
Nothing published for this version
This alpha release updates the Redux core package dependency to 5.0.0-alpha.2. This release _may_ have breaking changes.
This alpha release updates the Redux core package dependency to 5.0.0-alpha.2. This release may have breaking changes.
We've updated the redux dependency from 4.2.x to redux@5.0.0-alpha.2. The Redux v5 branch contains the TS conversion work we did in 2019, a migration to full ESM package compatibility, and some additional types changes and internal tweaks.
In practice, these hopefully shouldn't affect most codebases, but that's why these are major versions and we're publishing these alphas :)
We'd like users to try out these alphas releases in your apps and let us know of any build/typing/runtime errors or compatibility problems!
Please see the Redux v5 alpha release notes for further details:
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.1...v2.0.0-alpha.2
This is an alpha release for Redux Toolkit 2.0. This release has breaking changes.
This is an alpha release for Redux Toolkit 2.0. This release has breaking changes.
As a literally-major part of the Redux Toolkit 2.0 alpha development work, we've migrated the package definition to be a full {type: "module"} ESM package (with CJS still included for compatibility purposes).
We've done local testing of the published package in several different build tools and environments:
We have not tested it in React Native projects yet, or other non-React projects.
So far, the package structure seems to work okay in each of those environments, but we ask the community to try out this alpha in your own projects and report any breakages you find!
While it's not strictly related to the ESM migration, one potential compat issue is that we no longer transpile any of our build artifacts (other than removing TS syntax), and we do use the optional chaining operator ( ?. ). It's likely that Webpack 4 will find the correct ESM build artifact, but not be able to parse that syntax. You'll need to either upgrade to Webpack 5, or modify your Webpack config to transpile the RTK build artifacts that are imported from node_modules.
Along with the RTK package, we've migrated redux-thunk to ESM as well and published that as 3.0.0-alpha.1. That release also drops the existing default export, and instead has named exports: import { thunk, withExtraArgument } from 'redux-thunk'.
This should not meaningfully affect RTK users, as configureStore already sets up the thunk middleware for you.
We've migrated our own test suite from Jest to Vitest, fixing a couple of compat issues.
Michel Weststrate, author of Immer, has published a roadmap for Immer 10.0. This includes modernization by dropping non-Proxy ES5 compat, dropping the default export, performance improvements, and more. We plan to include Immer 10 in RTK 2.0.
We're restarting discussion around possible additional changes to Reselect in a v5 major version, and would appreciate feedback on possible improvements there.
See the RTK 2.0 planning thread for other work we're considering for 2.0.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v2.0.0-alpha.0...v2.0.0-alpha.1
This alpha release revamps the build and publishing setup for the RTK Query OpenAPI Codegen, as well as merging _numerous_ PRs from external contribut
This alpha release revamps the build and publishing setup for the RTK Query OpenAPI Codegen, as well as merging numerous PRs from external contributors.
This should resolve many outstanding issues and feature requests.
This is the initial alpha release for Redux Toolkit 2.0. This release has breaking changes.
Please try this out and let us know of any build or runtime incompatibilities beyond the expected breaking changes!
See the RTK 2.0 planning issue for discussion of likely upcoming changes.
createReducer and createSlice.extraReducersAs described in the RTK v1.9.0 release notes, we've removed the object form for createReducer and createSlice.extraReducers. Use the "builder callback" form instead.
See the 1.9 release notes for examples of what the necessary changes look like, and details on the available codemod for automatically making this change to your source.
This release drops backwards-compatibility aspects for IE11 in our published package build artifacts:
All module formats (CJS and ESM) now contain code that targets the latest ES spec and no longer backwards-compiled to ES5 syntax
Later 2.0-alpha releases will add full Node ESM support with exports in package.json, and may contain other build artifact changes as well.
We've updated our own build process to use the latest ESBuild and TS versions.
This bugfix release rewrites the RTKQ hook TS types to significantly improve TS perf.
This bugfix release rewrites the RTKQ hook TS types to significantly improve TS perf.
A number of users had reported that Intellisense for RTKQ API objects was extremely slow (multiple seconds) - see discussion in #3214 . We did some perf investigation on user-provided examples, and concluded that the biggest factor to slow RTKQ TS perf was the calculation of hook names like useGetPokemonQuery, which was generating a large TS union of types.
We've rewritten that hook names type calculation to use mapped types and a couple of intersections. In a specific user-provided stress test repo, it dropped TS calculation time by 60% (2600ms to 1000ms).
There's more potential work we can do to improve things, but this seems like a major perf improvement worth shipping now.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.6...v1.9.7
This bugfix release adds a new dev-mode middleware to catch accidentally dispatching an action creator, adds a new listener middleware option around w
This bugfix release adds a new dev-mode middleware to catch accidentally dispatching an action creator, adds a new listener middleware option around waiting for forks, adds a new option to update provided tags when updateQueryData is used, reworks internal types to better handle uses with TS declaration output, and fixes a variety of small issues.
RTK already includes dev-mode middleware that check for the common mistakes of accidentally mutating state and putting non-serializable values into state or actions.
Over the years we've also seen a semi-frequent error where users accidentally pass an action creator reference to dispatch, instead of calling it and dispatching the action it returns.
We've added another dev-mode middleware that specifically catches this error and warns about it.
The listener middleware's listenerApi.fork() method now has an optional autoJoin flag that can be used to keep the effect from finishing until all active forked tasks have completed.
updateQueryData now has an updateProvidedTags option that will force a recalculation of that endpoint's provided tags. It currently defaults to false, and we'll likely turn that to true in the next major.
The builder.addCase method now throws an error if a type string is empty.
fetchBaseQuery now uses an alternate method to clone the original Request in order to work around an obscure Chrome bug.
The immutability middleware logic was tweaked to avoid a potential stack overflow.
The internal type imports have been reworked to try to fix "type portability" issues when used in combination with TS declaration outputs.
A couple additional types were exported to help with wrapping createAsyncThunk.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.5...v1.9.6
This bugfix release includes notable improvements to TS type inference when using the enhancers option in configureStore, and updates the listener mid
This bugfix release includes notable improvements to TS type inference when using the enhancers option in configureStore, and updates the listener middleware to only check predicates if the dispatched value is truly an action object.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.4...v1.9.5
This bugfix release includes tweaks to RTKQ options handling, tweaks for perf updates, dependency updates, and updates to our CI tooling.
This bugfix release includes tweaks to RTKQ options handling, tweaks for perf updates, dependency updates, and updates to our CI tooling.
Also, please check out our ongoing RTK 2.0 alpha releases! They have significant improvements to bundle size, ESM/CJS compatibility, TS typings, and reducer update performance. We're looking for real-world feedback on behavior, performance, and any issues you might run into.
Passing transformResponse as part of enhanceEndpoints can now override the TS type of the original data.
fetchBaseQuery now properly checks for a global responseHandler option.
RTK Query now uses Immer's original() to do comparisons inside of copyWithStructuralSharing, which should significantly speed up performance when applying changes from re-fetched data.
RTKQ's internal subscriptionUpdated action is now marked as batchable.
We've updated dependencies to Immer 9.0.21, Reselect 4.1.8, and Redux 4.2.1.
We've added a suite of example apps built with different frameworks such as CRA 4, CRA 5, Next, and Vite, as well as examples that check for compatibility in Node with CJS and ESM modes and with various TS module resolution modes.
arethetypeswrong automated CLI check by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3294attw CLI option to treat problems as non-errors by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3316responseHandler being used in fetchBaseQuery by @praxxis in https://github.com/reduxjs/redux-toolkit/pull/3137resetApiState by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/3333subscriptionUpdated as autobatched by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/3364Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.3...v1.9.4
This release fixes a couple issues with the skip/skipToken options for query hooks, and makes a small perf tweak to serializing query args.
This release fixes a couple issues with the skip/skipToken options for query hooks, and makes a small perf tweak to serializing query args.
We made a change in v1.9.0 that tried to make some skip behavior more consistent, including clearing out the cached data. However, we had overlooked that our own docs actually said "skipping a query will keep the cached data", and several users pointed this out as they'd been relying on that behavior.
We've reverted that change. Now, setting {skip: true} or skipToken for a query with existing results will keep the data value (reflecting the last successful query), but currentData will be undefined (reflecting the current settings).
We also identified and fixed an issue that could cause subscription entries to leak under a specific combination of timing and settings changes.
RTKQ relies on serializing query arguments to serve as the cache keys, with the default using JSON.stringify() + some logic for sorting keys. There was a report that in some apps, large query arg objects could take a while to stringify and this was being done repeatedly. We've added a WeakMap-based cache for query args to avoid re-serializing existing arg values.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.2...v1.9.3
This bugfix release fixes a memory leak in createListenerMiddleware, optimizes performance inside serializableMiddleware, adds new options for fetchBa
This bugfix release fixes a memory leak in createListenerMiddleware, optimizes performance inside serializableMiddleware, adds new options for fetchBaseQuery, adds support for path RegExp exclusions in serializableMiddleware and immutabilityMiddleware, and improves some TS types.
createListenerMiddleware had a memory leak that turned out to be due to use of Promise.race(). We've restructured the logic to fix that.
fetchBaseQuery now correctly combines global options with endpoint / default options in all cases.
fetchBaseQuery now supports a jsonReplacer option that will be used when processing JSON.
Both dev check middleware now support regular expressions in the ignoredPaths array in addition to strings. This adds extra flexibility in skipping certain fields.
The CaseReducer type was sometimes incorrectly inferring its return type in rare cases. That's been fixed.
The isAnyOf/isAllOf matcher function TS types have been tweaked to not require an individual first parameter. This allows spreading arrays of matchers as arguments, like const isLoading = isAnyOf(...interestingPendingThunksArray).
The serializableMiddleware now uses a WeakSet if available to cache values it's seen. This should significantly speed up checks against large state values in development builds.
ThunkWithReturnValue interface by @giomogna in https://github.com/reduxjs/redux-toolkit/pull/3108raceWithSignal method instead of Promise.race by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/3021Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.1...v1.9.2
This bugfix release fixes assorted issues that were reported with RTK 1.9.0, and adds a few additional requested tweaks and improvements.
This bugfix release fixes assorted issues that were reported with RTK 1.9.0, and adds a few additional requested tweaks and improvements.
The createAsyncThunk.withTypes function was fully broken (it type-checked correctly, but pointed to the wrong function due to a name shadowing issue). That now works correctly.
The maxRetries option for RTKQ was inadvertently filtering out 0 values, and those are now accepted.
fulfillWithValue had incorrect types that made it appear as if the data was nested an additional level deeper. The types are now correct.
The ActionCreatorWithoutPayload type was tweaked to force an error when an action creator is accidentally called with an argument, which happens in cases like onClick={todoAdded}. This avoids accidentally passing values like React event objects as the payload.
Timer handling for batchActions and autoBatchEnhancer now works in more JS runtime environments.
The TagDescription type is now exported from RTKQ.
API endpoints now have a .name field containing the endpoint name, such as "getPokemon".
Calling promise.abort() on a createAsyncThunk promise before an async condition resolves will now be treated as if the condition itself returned false, bailing out and not dispatching anything.
The merge option now receives a third argument containing {arg, baseQueryMeta, fulfilledTimeStamp, requestId}, in case that info is useful in deciding how to merge.
The @reduxjs/rtk-codemods package has been updated to fix cases where the createSliceBuilder codemod didn't preserve fields with function variable arguments, like [todoAdded]: adapter.addOne. That package has been updated to v0.0.3.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.0...v1.9.1
…performance, adds a new autoBatchEnhancer, deprecates the "object" syntax for createReducer and createSlice.extraReducers, deprecates and _removes_ br…
This feature release adds several new options for RTK Query's createApi and fetchBaseQuery APIs, adds a new upsertQueryData util, rewrites RTKQ's internals for improved performance, adds a new autoBatchEnhancer, deprecates the "object" syntax for createReducer and createSlice.extraReducers, deprecates and removes broken utils for getting running query promises, improves TS inference, exports additional types, and fixes a number of reported issues.
npm i @reduxjs/toolkit@latest
yarn add @reduxjs/toolkit@latest
We plan to start work on RTK 2.0 in the next few weeks. RTK 2.0 will focus on dropping legacy build compatibility and deprecated APIs, with some potential new features. See the linked discussion thread and give us feedback on ideas!
createReducer and createSlice.extraReducersRTK's createReducer API was originally designed to accept a lookup table of action type strings to case reducers, like { "ADD_TODO" : (state, action) => {} }. We later added the "builder callback" form to allow more flexibility in adding "matchers" and a default handler, and did the same for createSlice.extraReducers.
We intend to remove the "object" form for both createReducer and createSlice.extraReducers in RTK 2.0. The builder callback form is effectively the same number of lines of code, and works much better with TypeScript.
Starting with this release, RTK will print a one-time runtime warning for both createReducer and createSlice.extraReducers if you pass in an object argument.
As an example, this:
const todoAdded = createAction('todos/todoAdded');
createReducer(initialState, {
[todoAdded]: (state, action) => {}
})
createSlice({
name,
initialState,
reducers: {/* case reducers here */},
extraReducers: {
[todoAdded]: (state, action) => {}
}
})
should be migrated to:
createReducer(initialState, builder => {
builder.addCase(todoAdded, (state, action) => {})
})
createSlice({
name,
initialState,
reducers: {/* case reducers here */},
extraReducers: builder => {
builder.addCase(todoAdded, (state, action) => {})
}
})
To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax.
The codemods package is available on NPM as @reduxjs/rtk-codemods. It currently contains two codemods: createReducerBuilder and createSliceBuilder.
To run the codemods against your codebase, run npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js.
Examples:
npx @reduxjs/rtk-codemods createReducerBuilder ./src
npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts
We also recommend re-running Prettier on the codebase before committing the changes.
These codemods should work, but we would greatly appreciate testing and feedback on more real-world codebases!
<details> <summary> Object reducer codemod before/after examples </summary> Before:
createReducer(initialState, {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
});
const slice1 = createSlice({
name: "a",
initialState: {},
extraReducers: {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
}
})
After:
createReducer(initialState, (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
});
builder.addCase(todoAdded1b, (state, action) => action.payload);
})
const slice1 = createSlice({
name: "a",
initialState: {},
extraReducers: (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
});
builder.addCase(todoAdded1b, (state, action) => action.payload);
}
})
</details>
getRunningOperationPromises Deprecation and ReplacementIn v1.7.0, we added an api.util.getRunningOperationPromises() method for use with SSR scenarios, as well as a singular getRunningOperationPromise() method intended for possible use with React Suspense.
Unfortunately, in #2477 we realized that both those methods have a fatal flaw - they do not work with multiple stores in SSR.
As of this release, we are immediately marking getRunningOperationPromises() as deprecated and discouraging its use before we remove it completely in RTK 2.0! It will now throw both runtime and compile errors in development to enforce moving away from using it. However, we are leaving its existing behavior in production builds to avoid actual breakage.
The getRunningOperationPromise() util was experimental, and as far as we can tell not actually being used by anyone, so we are removing getRunningOperationPromise completely in this release.
As replacements, RTKQ now includes four new thunks attached to api.util:
getRunningQueryThunk(endpointName, queryArgs)getRunningMutationThunk(endpointName, fixedCacheKeyOrRequestId)getRunningQueriesThunk()getRunningMutationsThunk()Usages would typically change like this:
-await Promise.all(api.util.getRunningOperationPromises())
+await Promise.all(dispatch(api.util.getRunningQueriesThunk()))
createApi OptionscreateApi endpoints now have several additional options that can be passed in, some of which are intended to work together.
merge OptionRTKQ was built around the assumption that the server is the source of truth, and every refetch replaces the cached data on the client. There are use cases when it would be useful to merge an incoming response into the existing cached data instead, such as pagination or APIs that return varying results over time.
Query endpoints can now accept a merge(cachedData, responseData) callback that lets you do Immer-powered "mutations" to update the existing cached data instead of replacing it entirely.
Since RTKQ assumes that each response per key should replace the existing cache entry by default, the merge option is expected to be used with the serializeQueryArgs and forceRefetch options, as described below.
serializeQueryArgs OptionRTK Query always serializes the cache key value, and uses the string as the actual key for storing the cache entry. The default serialization is the name of the endpoint, plus either the primitive value or a stable-serialized object. An example might be state.api.queries['getPokemon("pikachu")'].
RTKQ already supported customization of this serialization behavior at the createApi level. Now, each endpoint can specify its own serializeQueryArgs method.
The per-endpoint serializeQueryArgs may return either a string, an object, a number, or a boolean. If it's a string, that value will be used as-is. Otherwise, the return value will be run through the default serialization logic. This simplifies the common case of stripping out a couple unwanted object fields from the cache key.
This option serves two main purposes: leaving out values that are passed in to an endpoint but not really part of the "key" conceptually (like a socket or client instance), and altering cache key behavior to use a single entry for the endpoint (such as in an infinite loading / pagination scenario).
Also, the defaultSerializeQueryArgs util is now exported.
getPost: build.query<Post, { id: string; client: MyApiClient }>({
queryFn: async ({ id, client }) => {
const post = await client.fetchPost(id)
return { data: post }
},
serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
const { id } = queryArgs
// This can return a string, an object, a number, or a boolean.
// If it returns an object, number or boolean, that value
// will be serialized automatically via `defaultSerializeQueryArgs`
return { id } // omit `client` from the cache key
// Alternately, you can use `defaultSerializeQueryArgs`:
// return defaultSerializeQueryArgs({
// endpointName,
// queryArgs: { id },
// endpointDefinition
// })
// Or create and return a string yourself:
// return `getPost(${id})`
},
}),
forceRefresh optionSometimes you may want to force a refetch, even though RTKQ thinks that the serialized query args haven't changed and there's already a fulfilled cache entry.
This can be used to force RTKQ to actually refetch. One expected use case is an "infinite pagination" scenario where there is one cache entry for the endpoint, different page numbers are given as query args, and the incoming responses are merged into the existing cache entry:
listItems: build.query<string[], number>({
query: (pageNumber) => `/listItems?page=${pageNumber}`,
// Only have one cache entry because the arg always maps to one string
serializeQueryArgs: ({ endpointName }) => {
return endpointName
},
// Always merge incoming data to the cache entry
merge: (currentCache, newItems) => {
currentCache.push(...newItems)
},
// Refetch when the page arg changes
forceRefetch({ currentArg, previousArg }) {
return currentArg !== previousArg
},
}),
transformErrorResponse OptionSimilar to transformResponse, endpoints can now specify a transformErrorResponse option as well.
upsertQueryData UtilRTKQ already has an updateQueryData util to synchronously modify the contents of an existing cache entry, but there was no way to create a new cache entry and its metadata programmatically.
This release adds a new api.util.upsertQueryData API that allows creating a cache entry + its data programmatically. As with the other util methods, this is a thunk that should be dispatched, and you should pass in the exact cache key arg and complete data value you want to insert:
dispatch(
api.util.upsertQueryData('post', '3', {
id: '3',
title: 'All about cheese.',
contents: 'I love cheese!',
})
)
The dispatch acts like all other RTKQ requests, so the process is async, and the thunk returns a promise that resolves when the upsert is complete.
We've significantly rewritten RTK Query's internal implementation to improve performance, especially in cases where many components with query hooks mount at the same time. The middleware has been "flattened" and runs fewer internal checks against each action, subscription updates are grouped together, and some unnecessary memoized selectors have been removed. One consequence is that forgetting to add the RTKQ middleware now throws an error instead of logging a warning.
Overall, RTK Query processing time should be noticeably faster than it was in 1.8.
RTK Query also can take advantage of the new "auto-batch enhancer" (described below) for some additional perf optimization, and we recommend adding that to your Redux store configuration.
fetchBaseQuery OptionsfetchBaseQuery has several new options for processing requests:
You can now specify a timeout option for both individual endpoints and fetchBaseQuery . If provided, requests that take longer than this value will automatically abort.
fetchBaseQuery now supports passing the responseHandler and validateStatus options directly to fetchBaseQuery itself, in addition to accepting it as part of specific endpoints. If provided, these options will be applied as defaults to all requests for that API, which simplifies using them on many endpoints. Providing them for endpoints overrides the global option.
You can now specify a jsonContentType string that will be used to set the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to "application/json".
You can now specify a isJsonContentType callback that checks to see if the request body or response body should be stringified. The default looks for values like "application/json" and "application/vnd.api+json". You can also now specify responseHandler: 'content-type' to have RTKQ automatically check to see whether a response should be treated as text or JSON.
The prepareHeaders method can now return void and does not have to return headers.
The refetch() methods now return a promise that can be awaited.
Query endpoints can now accept a retryCondition callback as an alternative to maxRetries. If you provide retryCondition, it will be called to determine if RTKQ should retry a failed request again.
There are several different ways to "batch actions" with Redux stores, ranging from reducers to debounced subscriber notifications.
RTK now includes a new autoBatchEnhancer() store enhancer that uses a variation on the "debounced notification" approach, inspired by React's technique of batching renders and determining if an update is low-priority or high-priority.
The enhancer looks for any actions tagged with an action.meta[SHOULD_AUTOBATCH] = true flag, and delays notifying subscribers until a queued callback runs. This means that if multiple "auto-batched" actions are dispatched in a row, there will be only one subscriber notification. However, if any "normal-priority" action without that flag are dispatched before the queued callback runs, the enhancer will notify subscribers immediately instead and ignore the callback.
This allows Redux users to selectively tag certain actions for effective batching behavior, making this purely opt-in on a per-action basis, while retaining normal notification behavior for all other actions.
The enhancer defaults to using requestAnimationFrame, but can also be configured to use queueMicrotask to run at the end of an event loop tick, setTimeout, or a user-provided callback.
RTK Query's internals have been updated to mark several key actions as batchable. While the enhancer is purely opt-in, benchmarks indicate that it can help speed up UI performance with RTK Query, especially when rendering many components with query hooks. We recommend adding this enhancer to your store setup if you're using RTK Query:
const store = configureStore({
reducer,
enhancers: (existingEnhancers) => {
// Add the autobatch enhancer to the store setup
return existingEnhancers.concat(autoBatchEnhancer())
},
})
Additionally, there's a prepareAutoBatched util that can be used to help add the SHOULD_AUTOBATCH flag to actions, designed for use with createSlice:
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
incrementBatched: {
// Batched, low-priority
reducer(state) {
state.value += 1
},
// Use the `prepareAutoBatched` utility to automatically
// add the `action.meta[SHOULD_AUTOBATCH]` field the enhancer needs
prepare: prepareAutoBatched<void>(),
},
// Not batched, normal priority
decrementUnbatched(state) {
state.value -= 1
},
},
})
RTK 1.9 now requires TS 4.2 or greater, and supports through TS 4.9.
The action type strings generated by createAction are now full TS template literals when possible.
There's now a createAsyncThunk.withTypes() method that creates a "pre-typed" version of createAsyncThunk with types like {state, dispatch, extra} baked in. This can be used to simplify customizing createAsyncThunk with the right types once during app setup.
RTK Query now exports TS types for "pre-typed hook results", for cases when you want to wrap the query/mutation hooks in your own code. Additionally, RTKQ also exports BaseQueryApi and exposes TS-only types for endpoint definitions.
configureStore now correctly infers changes to the store shape from any store enhancers, such as adding actual extra fields to store.
RTK now exports additional types from redux-thunk.
Manually initiated RTKQ promises should resolve correctly.
Previous API tags are removed before adding new ones, instead of accidentally merging them together.
invalidateTags works correctly when dealing with persisted query state.
isJsonContentType predicate to fetchBaseQuery by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/2331jsonContentType to fetchBaseQuery options by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/2403StoreEnhancers by @fostyfost in https://github.com/reduxjs/redux-toolkit/pull/2550refetch by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2212upsertQueryData race situations by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2646error. by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2743dispatchQueued variable after flushing by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2757forceRefetch to QueryExtraOptions by @schadenn in https://github.com/reduxjs/redux-toolkit/pull/2663prepareHeaders does not need to return headers any more by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2775codemods-cli and rewrite "object reducer" codemods by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2768skipToken behaviour in useQueryState by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2779fetchBaseQuery: allow headers option by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2778getRunningOperationPromise(s) with getRunning(Query|Queries|Mutation|Mutations)Thunk by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2481responseHandler and validateStatus configuration by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2823Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.8.6...v1.9.0
This release candidate updates the auto-batching enhancer to accept additional options for queuing subscriber notifications, and improves RTKQ perf by
This release candidate updates the auto-batching enhancer to accept additional options for queuing subscriber notifications, and improves RTKQ perf by removing some unnecessary internal memoized selectors.
Please try this out and give us feedback (even if it's just "tried updating and everything's fine")! If no further issues come up we intend to publish 1.9 in the next few days.
npm i @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
Docs updates for 1.9 are complete, and can be viewed here:
https://deploy-preview-2401--redux-starter-kit-docs.netlify.app/
The initial implementation of the autoBatchEnhancer() always queued delayed subscriber notifications using queueMicrotask. We've updated it to accept alternate options that queue with setTimeout, requestAnimationFrame, or bring-your-own-callback (more similar to redux-batched-subscribe).
The variation in JS event loop timing behavior (microtasks, macrotasks, and frames) means having these options may be useful in different situations.
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.0-rc.0...v1.9.0-rc.1
This release candidate includes a new "auto-batching" store enhancer, support for passing some global options to fetchBaseQuery, a fix for forceRefetc
This release candidate includes a new "auto-batching" store enhancer, support for passing some global options to fetchBaseQuery, a fix for forceRefetch behavior, and internal tweaks to checks for missing RTKQ middleware setup.
Please try this out and give us feedback (even if it's just "tried updating and everything's fine")! If no further issues come up we intend to publish 1.9 in the next few days.
npm i @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
Docs updates for 1.9 are complete, and can be viewed here:
https://deploy-preview-2401--redux-starter-kit-docs.netlify.app/
There are several different ways to "batch actions" with Redux stores, ranging from reducers to debounced subscriber notifications.
RTK now includes a new autoBatchEnhancer() store enhancer that uses a variation on the "debounced notification" approach, inspired by React's technique of batching renders and determining if an update is low-priority or high-priority.
The enhancer looks for any actions tagged with an action.meta[SHOULD_AUTOBATCH] = true flag, and delays notifying subscribers until the end of the event loop tick. This means that if multiple "auto-batched" actions are dispatched in a row, there will be only one subscriber notification. However, if any "normal-priority" action without that flag is dispatched in the same tick, the enhancer will notify subscribers immediately.
This allows Redux users to selectively tag certain actions for effective batching behavior, making this purely opt-in on a per-action basis, while retaining normal notification behavior for all other actions.
RTK Query's internals have been updated to mark several key actions as batchable. While the enhancer is purely opt-in, benchmarks indicate that it can help speed up UI performance with RTK Query, especially when rendering many components with query hooks. We recommend adding it to your store setup:
const store = configureStore({
reducer,
enhancers: (existingEnhancers) => {
// Add the autobatch enhancer to the store setup
return existingEnhancers.concat(autoBatchEnhancer())
},
})
Additionally, there's a prepareAutoBatched util that can be used to help add the SHOULD_AUTOBATCH flag to actions, designed for use with createSlice:
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
incrementBatched: {
// Batched, low-priority
reducer(state) {
state.value += 1
},
// Use the `prepareAutoBatched` utility to automatically
// add the `action.meta[SHOULD_AUTOBATCH]` field the enhancer needs
prepare: prepareAutoBatched<void>(),
},
// Not batched, normal priority
decrementUnbatched(state) {
state.value -= 1
},
},
})
fetchBaseQuery Global OptionsfetchBaseQuery now supports passing the responseHandler, validateStatus, and timeout options directly to fetchBaseQuery itself, in addition to accepting it as part of specific endpoints. If provided, these options will be applied as defaults to all requests for that API, which simplifies using them on many endpoints.
Providing serializeQueryArgs and forceRefetch options for an endpoint now works correctly when you pass an object as the cache key argument to a query hook.
The defaultSerializeQueryArgs util is now exported.
The endpoint-specific serializeQueryArgs option now allows returning an object or a number instead of just a string. If a string is returned, it will be used as-is for the serialized cache key. If an object or number is returned, that value will be passed to defaultSerializeQueryArgs. This simplifies the common case of wanting to remove a couple fields from the cache key, without needing to call defaultSerializeQueryArgs yourself.
Internal tweaks to the RTKQ middleware behavior for detecting cases where the middleware has not been added to the store.
The API docs for the 1.9 preview are fully updated.
responseHandler and validateStatus configuration by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2823Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.0-beta.0...v1.9.0-rc.0
…tweaks and additional type exports, a runtime deprecation warning for the object argument form of createReducer and createSlice.extraReducers, and cod…
This feature-complete preview release includes several new options for RTK Query API endpoints as well as the ability to "upsert" data, performance improvements to the RTK Query middleware, improvements to fetchBaseQuery behavior, several TS types tweaks and additional type exports, a runtime deprecation warning for the object argument form of createReducer and createSlice.extraReducers, and codemods to update those methods.
Please try this out and give us feedback (even if it's just "tried updating and everything's fine")! We believe that all changes intended for 1.9 are stable and should work, but as always we'd appreciate real-world checks to confirm that.
npm i @reduxjs/toolkit@next
yarn add @reduxjs/toolkit@next
Docs updates for 1.9 are in progress and can be viewed here:
https://deploy-preview-2401--redux-starter-kit-docs.netlify.app/
Per the description in 1.9.0-alpha.0, we plan to remove the "object" argument from createReducer and createSlice.extraReducers in the future RTK 2.0 major version. In 1.9.0-alpha.0, we added a one-shot runtime warning to each of those APIs.
To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax.
The codemods package is available on NPM as @reduxjs/rtk-codemods. It currently contains two codemods: createReducerBuilder and createSliceBuilder.
To run the codemods against your codebase, run npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js.
Examples:
npx @reduxjs/rtk-codemods createReducerBuilder ./src
npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts
We also recommend re-running Prettier on the codebase before committing the changes.
These codemods should work, but we would greatly appreciate testing and feedback on more real-world codebases!
Before:
createReducer(initialState, {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
});
const slice1 = createSlice({
name: "a",
initialState: {},
extraReducers: {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
}
})
After:
createReducer(initialState, (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
});
builder.addCase(todoAdded1b, (state, action) => action.payload);
})
const slice1 = createSlice({
name: "a",
initialState: {},
extraReducers: (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
});
builder.addCase(todoAdded1b, (state, action) => action.payload);
}
})
getRunningOperationPromises Deprecation and ReplacementIn v1.7.0, we added an api.util.getRunningOperationPromises() method for use with SSR scenarios, as well as a singular getRunningOperationPromise() method intended for possible use with React Suspense.
Unfortunately, in #2477 we realized that both those methods have a fatal flaw - they do not work with multiple stores in SSR.
As of this release, we are immediately marking getRunningOperationPromises() as deprecated and discouraging its use before we remove it completely in RTK 2.0! It will now throw both runtime and compile errors in development to enforce moving away from using it. However, we are leaving its existing behavior in production builds to avoid actual breakage.
The getRunningOperationPromise() util was experimental, and as far as we can tell not actually being used by anyone, so we are removing getRunningOperationPromise completely in this release.
As replacements, RTKQ now includes four new thunks attached to api.util:
getRunningQueryThunk(endpointName, queryArgs)getRunningMutationThunk(endpointName, fixedCacheKeyOrRequestId)getRunningQueriesThunk()getRunningMutationsThunk()Usages would typically change like this:
-await Promise.all(api.util.getRunningOperationPromises())
+await Promise.all(dispatch(api.util.getRunningQueriesThunk()))
See the previous release notes for more details.
serializeQueryArgs option ( #2493 )merge option ( #1059 )forceRefetch option ( #2663 )transformErrorResponse option ( #1841upsertQueryData util ( #2266 )fetchBaseQuery options:
jsonContentType ( #2403 )timeout ( #2363 )content-type response handler ( #2363 )prepareHeaders can return void ( #2775 )createAsyncThunk.withTypes ( #2604 )Redux Toolkit now requires TypeScript 4.2 or higher, and works correctly with TS 4.8.
This feature preview release fixes broken behavior in the new upsertQueryData API, fixes behavior with the serializeQueryArgs+merge combination by add
This feature preview release fixes broken behavior in the new upsertQueryData API, fixes behavior with the serializeQueryArgs+merge combination by adding a new forceRefetch option, rewrites the internal subscription tracking to speed up mount/update times, adds new TS type exports, and includes the bug fixes from 1.8.6.
upsertQueryData FixWe released the new upsertQueryData util in 1.9.0-alpha.1, but the behavior didn't actually work as intended in some cases. We've tweaked the implementation and it now should work correctly. Please try it out and let us know!
forceRefresh option and Infinite Loading UsagesIn earlier alphas, we added a new serializeQueryArgs endpoint option to allow customization of cache keys. This serves two purposes: leaving out values that are passed in to an endpoint but not really part of the "key" conceptually (like a socket or client instance), and altering cache key behavior to use a single entry for the endpoint such as in an infinite loading / pagination scenario.
Along with that, we also added a merge option that lets you modify the contents of an existing cache entry when new data is received, instead always replacing it.
Due to the existing internal logic, these two options are insufficient for the infinite loading / pagination case. For example, changing useGetItemsQuery(pageNum) from 1 to 2 starts the checks for fetching new data, but it bails out internally because there's already a cache entry that is status: fulfilled for that endpoint and cache key.
We've added an additional forceRefresh call back that receives {currentArg, previousArg, state, endpointState} as arguments. Use this in combination with the other options to force this endpoint to refetch when args change despite a single cache entry already existing, such as this example:
forceRefetch({currentArg, previousArg}) {
// Assume these are page numbers
return currentArg !== previousArg
},
serializeQueryArgs({endpointName}) {
// Will only have one cache entry for this endpoint, because of the consistent name
return endpointName
},
merge(currentCacheData, responseData) {
// Always add incoming data to the existing cache entry
currentCacheData.push(...responseData)
}
The forceRefresh option may also be useful in other app-specific scenarios as well.
RTKQ tracks subscription entries, and thus far has done so by saving them in the Redux state and updating that by dispatching actions as each query hook loads. We've seen that this can be a performance bottleneck in edge cases where hundreds of query hooks are being mounted at once. (This shouldn't be a concern in most apps, but some users were stress-testing things :) )
We've reworked the internal RTKQ middleware logic to track most of the subscription data inside the middleware and sync it to the Redux store at the end of an event loop tick. This should speed up those large list edge cases by cutting 90% of the startup time.
upsertQueryData race situations by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2646error. by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2743dispatch type inference to correctly handle read-only middleware arrays by @dokmic in https://github.com/reduxjs/redux-toolkit/pull/2629dispatchQueued variable after flushing by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/2757forceRefetch to QueryExtraOptions by @schadenn in https://github.com/reduxjs/redux-toolkit/pull/2663Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.9.0-alpha.1...v1.9.0-alpha.2
Your coding agent can read these notes before it upgrades. Set up the MCP server →