note: la sintesi e le note di rilascio sono in inglese
pending: sintesi in attesa
Rilevata il 2026-12-04 alle 05:55 UTC. La sintesi viene scritta al prossimo aggiornamento; le note di rilascio complete sono già qui sotto.
release-notesgithub.com/reduxjs/redux-toolkit · 191 righe
- This **feature release** updates Immer to 11.2.14 for major reducer and RTK Query cache update perf improvements, adds an options argument to `upsertQueryEntries` for safer writes while fetches are in flight, adds a guarded `undo` for optimistic updates, adds `api.util.removeQueryData`, lets `refetchOnFocus` and `refetchOnReconnect` take a max data age in seconds, makes `prefetch` return a promise, fixes lost invalidations under `invalidationBehavior: 'immediately'`, adds `checkCurrent` and better error reporting to the listener middleware, fixes two regressions from 2.15.0 around memory use and `retainFor`, and includes several smaller fixes plus a new docs page on when queries run and refetch.
- This release continues the work from our [roadmap to Redux Toolkit 3.0](https://github.com/reduxjs/redux-toolkit/discussions/5536).
- ## Changelog
- ### Immer 11.2.14 Perf Improvements
- We've updated our Immer dependency to [11.2.14](https://github.com/immerjs/immer/releases/tag/v11.2.14), which has another round of significant perf improvements. Since every `createSlice` reducer and every RTK Query cache update runs through Immer, this should speed up most Redux apps with no code changes.
- We expanded Immer's benchmark suite to cover more realistic scenarios: frozen initial state (which is what you have in a real Redux store), chained updates, 10k-item arrays, and storing large API responses the way RTK Query does. Running it showed several places where Immer was doing far more work than it needed to:
- - **Freezing:** Immer used to deep-freeze the entire result after every update, walking every object in the tree even when it hadn't changed and was already frozen. It now freezes each modified copy as it finalizes, and only walks values that are actually new.
- - **Copying frozen arrays:** copying a frozen array with `slice()` turned out to be much slower in V8 than spread syntax, so Immer now uses spread.
- - **Iteration:** Immer 11.0 made loose iteration (`Object.keys`) the default, but a rewrite in the same release accidentally kept the finalize step on the slower strict iteration path. It now follows the setting again, so you get the faster iteration that was intended all along.
- - **Walking new data and proxy traps:** finalize skips primitives early and uses index loops when walking newly assigned data, and the proxy `get` and `set` traps do less work per access.
- Comparing Immer 11.2.13 to 11.2.14 with auto-freeze on, from Immer's benchmark suite:
- | Scenario | Speedup |
- | --- | --- |
- | 10k array: toggle one item | 91x (1.04ms → 11.4µs) |
- | 10k array: 10 chained toggles | 89x |
- | 10k array: add an item | 33x |
- | 10k array: update via `find` | 2.7x |
- | 100 items: update | 8.9x |
- | RTKQ-style action sequence | 4.8x |
- | Store a new 1k-item API response | 2.0x |
- Immer also has [an optional `enableArrayMethods` plugin](https://immerjs.github.io/immer/array-methods), which RTK does _not_ turn on by default. With that plugin enabled, 11.2.14 makes array reordering much faster: removing one item from a 10k-item array is 143x faster, and 10 chained removes are 209x faster. If your app does a lot of array updates in reducers, you can opt in by calling `enableArrayMethods()` from `immer` once at startup.
- See the [Immer 11.2.14 release notes](https://github.com/immerjs/immer/releases/tag/v11.2.14) for details, including edge case behaviors.
- ### `upsertQueryEntries` Options for In-Flight Fetches
- We've had reports that pushing data into the cache from a websocket or other external source didn't play well with fetches that were already running. `upsertQueryEntries` wrote the new value, then the older fetch resolved and overwrote it with stale data. The upsert also marked the entry as fulfilled, cleared any error, and restarted the `keepUnusedDataFor` timer, which isn't always what you want for a background update.
- `upsertQueryEntries` now takes an optional second argument with three boolean options. All default to `false`, so existing behavior is unchanged:
- - **`ignoreEarlierFetches`**: a fetch that was already running when the upsert happened has its data ignored when it resolves. If that fetch fails, it still sets the entry's status and error. Fetches started _after_ the upsert are not affected. This also covers fetches started by `upsertQueryData`.
- - **`keepRequestState`**: existing entries keep their `status`, `requestId`, `error`, and timestamps. Only the data and provided tags change. Entries that don't exist yet are created as fulfilled.
- - **`keepUnusedDataTimer`**: existing entries don't get their `keepUnusedDataFor` timer restarted. New entries with no subscribers get the normal timer.
- ```ts
- socket.on('postUpdated', (post) => {
- dispatch(
- api.util.upsertQueryEntries(
- [{ endpointName: 'getPost', arg: { id: post.id }, value: post }],
- { ignoreEarlierFetches: true, keepRequestState: true },
- ),
- )
- })
- ```
- Note that when a fetch's result is ignored, its `initiate()` promise resolves with the current cache entry, which holds the upserted data. The options type is exported as `UpsertEntriesOptions`.
- ### Guarded `undo` for Optimistic Updates
- The standard optimistic update pattern calls `patchResult.undo()` when the mutation fails. If a refetch or another cache write replaced the data in the meantime, that undo applied its inverse patches on top of newer data and could corrupt it ([#5513](https://github.com/reduxjs/redux-toolkit/issues/5513)).
- The `undo` returned by `updateQueryData` now accepts `{ ifUnchanged: true }`. It only applies the inverse patches if the cached data is still the same value this update stored. If something else has replaced the data, or the entry was removed, the undo does nothing. Plain `undo()` keeps the existing unconditional behavior, so `queryFulfilled.catch(patchResult.undo)` still works as before.
- With several overlapping optimistic updates, skipping an older undo can leave a failed mutation's changes in the cache. We recommend pairing the guarded undo with an invalidation on error, so the cache ends up matching the server either way:
- ```ts
- async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
- const patchResult = dispatch(
- api.util.updateQueryData('getPost', id, (draft) => {
- Object.assign(draft, patch)
- }),
- )
- try {
- await queryFulfilled
- } catch {
- patchResult.undo({ ifUnchanged: true })
- dispatch(api.util.invalidateTags(['Post']))
- }
- }
- ```
- Thanks to @dagemawinegash for implementing this!
- ### `api.util.removeQueryData`
- We've had a long-standing request for a way to remove a single cache entry ([#2820](https://github.com/reduxjs/redux-toolkit/issues/2820)). `api.util.removeQueryData(endpointName, arg, options?)` does that:
- ```ts
- const removed = dispatch(
- api.util.removeQueryData('getPost', 5, { onlyIfUnused: true }),
- )
- ```
- It runs synchronously and returns `true` if an entry was removed. With `onlyIfUnused: true`, it skips entries that still have subscribers and returns `false`. It uses the endpoint's `serializeQueryArgs` and works for infinite queries.
- Removal does the same cleanup as automatic cache expiry: it aborts a running request, clears timers and polling, and resolves `cacheEntryRemoved`. Mounted `useQuery`, `useQuerySubscription`, and `useInfiniteQuery` hooks go back to `isLoading` and refetch. Lazy query hooks reset to uninitialized and don't refetch. Subscriptions created with `initiate()` are dropped.
- In most cases you probably want one of the existing tools instead: `keepUnusedDataFor`, invalidation or `refetch`, `resetApiState`, or `currentData`. The docs list those first. Thanks to @riqts for the earlier proposal in #4216 that this builds on.
- ### `refetchOnFocus` / `refetchOnReconnect` Max Age, and `prefetch` Returns a Promise
- `refetchOnFocus` and `refetchOnReconnect` now accept a number of seconds as well as a boolean, at the `createApi`, hook, and `initiate()` subscription levels ([#5585](https://github.com/reduxjs/redux-toolkit/issues/5585)). With a number, the entry only refetches on focus or reconnect if its data is at least that old, or if it has no data. `0` behaves like `true`. When several subscribers use different values, the entry refetches if any of them would.
- ```ts
- // Only refetch on focus if the data is more than 60 seconds old
- useGetPostsQuery(undefined, { refetchOnFocus: 60 })
- ```
- `api.util.prefetch` and the callback from `usePrefetch` now return a promise ([#5580](https://github.com/reduxjs/redux-toolkit/issues/5580)). It resolves when the request finishes, joins a request that's already running, and resolves right away if no fetch was needed. It never rejects; check the cache entry if you need to know about errors.
- ```ts
- await dispatch(api.util.prefetch('getPost', 5, { ifOlderThan: 30 }))
- ```
- `prefetch` and `usePrefetch` also work on infinite query endpoints now. They fetch the first page when there's no cached data, and refetch like a normal infinite query refetch when there is.
- ### `invalidationBehavior: 'immediately'` Catches Invalidations During a Running Request
- With `invalidationBehavior: 'immediately'`, an invalidation that arrived while a query was running could be lost. If that query didn't provide the invalidated tag yet (its first fetch, or a refetch whose result starts providing the tag), nothing refetched it, and the entry kept showing pre-mutation data.
- RTKQ now tracks tags invalidated while queries are running. When a request settles, if any tags it now provides were invalidated after the request started, the entry is refetched if it has subscribers, or removed if it doesn't. Several invalidations during one request produce one refetch. This covers infinite queries too.
- The default `'delayed'` behavior is unchanged. **If your app cares about stale data after mutations, we recommend trying `invalidationBehavior: 'immediately'`.** It avoids holding back invalidations while queries are running ([#4347](https://github.com/reduxjs/redux-toolkit/issues/4347), [#3979](https://github.com/reduxjs/redux-toolkit/issues/3979), [#4794](https://github.com/reduxjs/redux-toolkit/issues/4794)), and we plan to make it the only behavior in 3.0.
- ### Listener Middleware Updates
- `take` and `condition` now accept an options object as their second argument, `{ timeout?, checkCurrent? }`, in addition to a plain timeout number ([#5523](https://github.com/reduxjs/redux-toolkit/issues/5523)). With `checkCurrent: true`, the predicate is first called with the triggering action and the current state. If it matches, `condition` resolves `true` immediately and `take` resolves with `[triggeringAction, currentState, currentState]`. Otherwise it waits as usual.
- ```ts
- await listenerApi.condition((action, current) => current.auth.ready, {
- checkCurrent: true,
- timeout: 5000,
- })
- ```
- Be careful with predicates that only check the action type: they can match the triggering action itself.
- **Behavior change:** errors thrown by forked tasks with `autoJoin: true` (including nested forks) are now reported to `onError`, with a new `raisedBy: 'fork'` value. Before, they were silently dropped unless you read `task.result`. The error still doesn't change the task's result or fail the parent listener, and cancellations are not reported. **If your `onError` handler switches on `raisedBy`, it will now see `'fork'` in addition to `'effect'` and `'predicate'`.** Thanks to @wozhenbang2004 for both of these changes!
- We also fixed `ForkedTask.result` rejecting with a `listener-completed` `TaskAbortError` after the task had already finished. This happened whenever the listener didn't await the result itself, which was every time with `autoJoin: true`. A settled task now keeps its `{ status: 'ok', value }` or `{ status: 'rejected', error }` result. It only rejects if the listener is cancelled or completes while the task is still running.
- The listener middleware docs now cover `checkCurrent`, the rules for when `ForkedTask.result` rejects, and how duplicate listeners are detected.
- ### 2.15.0 Regression Fixes
- 2.15.0 had two regressions in RTKQ's subscription and request tracking.
- `initiate()` results kept the settled store state alive. Each running request holds a promise that resolves with the root state, and the result's `abort` function closed over that request. So every `initiate()` result your code held onto (arrays passed to `Promise.all`, refs, SSR code awaiting `getRunningQueriesThunk()`) kept a full state snapshot in memory, and memory use grew quadratically with concurrent requests. In a benchmark with 2000 concurrent fetches, retained memory after GC dropped from 356 MB to 23 MB. `abort` now looks up the running request when it's called.
- `retainFor` applied on every later unsubscribe instead of once. It stayed on the cache entry, so each later unsubscribe kept the entry for the longer of `keepUnusedDataFor` and `retainFor`. Now `retainFor` sets a deadline once, when the last subscriber leaves (or when the request settles if nothing subscribed). Later unsubscribes keep the entry until the later of that deadline and the normal `keepUnusedDataFor` timer. We also fixed an unsubscribe during a `retainFor` fetch removing the entry and aborting the request.
- ### Other Fixes
- The default `retry` backoff left an abort listener attached to the request's signal after each delay finished, so they piled up across attempts and stayed attached after the request succeeded or ran out of retries ([#5656](https://github.com/reduxjs/redux-toolkit/issues/5656)). The listener is now removed when each delay ends. Thanks @FullStraing!
- `WritableNonArrayDraft` is now exported from the package root. `WritableDraft` resolves to it for non-array objects, so projects with `declaration: true` got TS4023/TS4058 errors when exporting an inferred slice or its actions ([#5650](https://github.com/reduxjs/redux-toolkit/issues/5650)). Thanks @draarivpatel-ui!
- `copyWithStructuralSharing` reused the old object when the new one had the same number of keys but different key names with `undefined` values, such as `{ filterId: '1' }` → `{ address: undefined }`. That made `useLazyQuery` keep the old arg and show the old cache entry's data after `trigger()` with the new arg, and could keep stale `queryFn` results ([#5271](https://github.com/reduxjs/redux-toolkit/issues/5271)). It now only reuses the old value when the key exists on the old object. Thanks @itisrmk!
- `upsertQueryData` on an infinite query entry with more than one cached page could nest the upserted `{ pages, pageParams }` object as extra pages, because the upsert went through the cached-page refetch loop. Upserts now skip that loop. Thanks @dfedoryshchev!
- `autoBatchEnhancer` tracked subscribers by callback, so subscribing the same callback twice only notified it once per batch, and unsubscribing either registration silenced both ([#5659](https://github.com/reduxjs/redux-toolkit/issues/5659)). A listener that subscribed or unsubscribed other callbacks could also change which callbacks ran partway through a notification. Each subscription is now tracked separately, and changes made during a notification take effect on the next one, matching the core Redux store. Thanks @git-abhijeet!
- If an infinite query started with an `initialPageParam` passed at the call site (hook option or `initiate()` option) and its first page failed, the next `refetch()`, `fetchNextPage()`, poll, or invalidation used the endpoint's `initialPageParam` instead. That value is now stored on the cache entry and reused. Thanks @kkatalz!
- ### Docs Updates
- There's a new [Request Behavior](https://redux-toolkit.js.org/rtk-query/usage/request-behavior) usage page that covers when a call starts a request, joins a running one, or uses cached data; which option wins when several force a refetch; what triggers refetches; and how `retry` options combine. It includes a comparison table for people coming from TanStack Query. The Cache Behavior page now focuses on how long data is kept, including `retainFor` and the ways an entry gets removed early, and the Automated Re-fetching page replaces the big tag matching matrix with the two rules behind it.
- The `useQueryState` result type signature in the docs is now correct (thanks @FullStraing!).
- ## What's Changed
- * feat(toolkit): add checkCurrent to listener take and condition by @wozhenbang2004 in https://github.com/reduxjs/redux-toolkit/pull/5630
- * fix(toolkit): report errors from autoJoined listener tasks by @wozhenbang2004 in https://github.com/reduxjs/redux-toolkit/pull/5631
- * Add `api.util.removeQueryData` by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5632
- * Keep a forked task's outcome when its listener finishes after the task settles by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5639
- * Add a seconds value for `refetchOnFocus`/`refetchOnReconnect`, and return a promise from `prefetch` by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5638
- * Refetch entries invalidated while their request is running under `invalidationBehavior: 'immediately'` by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5640
- * feat(query): add guarded undo for optimistic updates by @dagemawinegash in https://github.com/reduxjs/redux-toolkit/pull/5599
- * Add options argument to `upsertQueryEntries` for in-flight fetches by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5641
- * Stop `initiate()` results from keeping the settled store state alive by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5642
- * Count retainFor once instead of on every later unsubscribe by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5643
- * fix(types): export WritableNonArrayDraft by @draarivpatel-ui in https://github.com/reduxjs/redux-toolkit/pull/5651
- * fix(query): release abort listeners after retry backoff by @FullStraing in https://github.com/reduxjs/redux-toolkit/pull/5657
- * fix(query): don't reuse an object with different keys in copyWithStructuralSharing by @itisrmk in https://github.com/reduxjs/redux-toolkit/pull/5652
- * fix(toolkit): keep the hook's `initialPageParam` on infinite query refetch and `fetchNextPage` by @kkatalz in https://github.com/reduxjs/redux-toolkit/pull/5627
- * fix(toolkit): don't refetch cached pages when upserting an infinite query by @dfedoryshchev in https://github.com/reduxjs/redux-toolkit/pull/5625
- * Preserve independent subscriptions during batched notifications by @git-abhijeet in https://github.com/reduxjs/redux-toolkit/pull/5660
- * Bump Immer to 11.2.14 to pick up perf improvements by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5662
- **Full Changelog**: https://github.com/reduxjs/redux-toolkit/compare/v2.15.0...v2.16.0