Repository navigation
v2.16.0 #5663
markerikson
announced in
Announcements
v2.16.0
#5663
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
This feature release updates Immer to 11.2.14 for major reducer and RTK Query cache update perf improvements, adds an options argument to
upsertQueryEntriesfor safer writes while fetches are in flight, adds a guardedundofor optimistic updates, addsapi.util.removeQueryData, letsrefetchOnFocusandrefetchOnReconnecttake a max data age in seconds, makesprefetchreturn a promise, fixes lost invalidations underinvalidationBehavior: 'immediately', addscheckCurrentand better error reporting to the listener middleware, fixes two regressions from 2.15.0 around memory use andretainFor, 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.
Changelog
Immer 11.2.14 Perf Improvements
We've updated our Immer dependency to 11.2.14, which has another round of significant perf improvements. Since every
createSlicereducer 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:
slice()turned out to be much slower in V8 than spread syntax, so Immer now uses spread.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.getandsettraps do less work per access.Comparing Immer 11.2.13 to 11.2.14 with auto-freeze on, from Immer's benchmark suite:
findImmer also has an optional
enableArrayMethodsplugin, 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 callingenableArrayMethods()fromimmeronce at startup.See the Immer 11.2.14 release notes for details, including edge case behaviors.
upsertQueryEntriesOptions for In-Flight FetchesWe'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.
upsertQueryEntrieswrote 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 thekeepUnusedDataFortimer, which isn't always what you want for a background update.upsertQueryEntriesnow takes an optional second argument with three boolean options. All default tofalse, 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 byupsertQueryData.keepRequestState: existing entries keep theirstatus,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 theirkeepUnusedDataFortimer restarted. New entries with no subscribers get the normal timer.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 asUpsertEntriesOptions.Guarded
undofor Optimistic UpdatesThe 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).The
undoreturned byupdateQueryDatanow 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. Plainundo()keeps the existing unconditional behavior, soqueryFulfilled.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:
Thanks to @dagemawinegash for implementing this!
api.util.removeQueryDataWe've had a long-standing request for a way to remove a single cache entry (#2820).
api.util.removeQueryData(endpointName, arg, options?)does that:It runs synchronously and returns
trueif an entry was removed. WithonlyIfUnused: true, it skips entries that still have subscribers and returnsfalse. It uses the endpoint'sserializeQueryArgsand 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. MounteduseQuery,useQuerySubscription, anduseInfiniteQueryhooks go back toisLoadingand refetch. Lazy query hooks reset to uninitialized and don't refetch. Subscriptions created withinitiate()are dropped.In most cases you probably want one of the existing tools instead:
keepUnusedDataFor, invalidation orrefetch,resetApiState, orcurrentData. The docs list those first. Thanks to @riqts for the earlier proposal in #4216 that this builds on.refetchOnFocus/refetchOnReconnectMax Age, andprefetchReturns a PromiserefetchOnFocusandrefetchOnReconnectnow accept a number of seconds as well as a boolean, at thecreateApi, hook, andinitiate()subscription levels (#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.0behaves liketrue. When several subscribers use different values, the entry refetches if any of them would.api.util.prefetchand the callback fromusePrefetchnow return a promise (#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.prefetchandusePrefetchalso 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 RequestWith
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 tryinginvalidationBehavior: 'immediately'. It avoids holding back invalidations while queries are running (#4347, #3979, #4794), and we plan to make it the only behavior in 3.0.Listener Middleware Updates
takeandconditionnow accept an options object as their second argument,{ timeout?, checkCurrent? }, in addition to a plain timeout number (#5523). WithcheckCurrent: true, the predicate is first called with the triggering action and the current state. If it matches,conditionresolvestrueimmediately andtakeresolves with[triggeringAction, currentState, currentState]. Otherwise it waits as usual.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 toonError, with a newraisedBy: 'fork'value. Before, they were silently dropped unless you readtask.result. The error still doesn't change the task's result or fail the parent listener, and cancellations are not reported. If youronErrorhandler switches onraisedBy, it will now see'fork'in addition to'effect'and'predicate'. Thanks to @wozhenbang2004 for both of these changes!We also fixed
ForkedTask.resultrejecting with alistener-completedTaskAbortErrorafter the task had already finished. This happened whenever the listener didn't await the result itself, which was every time withautoJoin: 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 whenForkedTask.resultrejects, 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'sabortfunction closed over that request. So everyinitiate()result your code held onto (arrays passed toPromise.all, refs, SSR code awaitinggetRunningQueriesThunk()) 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.abortnow looks up the running request when it's called.retainForapplied on every later unsubscribe instead of once. It stayed on the cache entry, so each later unsubscribe kept the entry for the longer ofkeepUnusedDataForandretainFor. NowretainForsets 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 normalkeepUnusedDataFortimer. We also fixed an unsubscribe during aretainForfetch removing the entry and aborting the request.Other Fixes
The default
retrybackoff 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). The listener is now removed when each delay ends. Thanks @FullStraing!WritableNonArrayDraftis now exported from the package root.WritableDraftresolves to it for non-array objects, so projects withdeclaration: truegot TS4023/TS4058 errors when exporting an inferred slice or its actions (#5650). Thanks @draarivpatel-ui!copyWithStructuralSharingreused the old object when the new one had the same number of keys but different key names withundefinedvalues, such as{ filterId: '1' }→{ address: undefined }. That madeuseLazyQuerykeep the old arg and show the old cache entry's data aftertrigger()with the new arg, and could keep stalequeryFnresults (#5271). It now only reuses the old value when the key exists on the old object. Thanks @itisrmk!upsertQueryDataon 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!autoBatchEnhancertracked subscribers by callback, so subscribing the same callback twice only notified it once per batch, and unsubscribing either registration silenced both (#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
initialPageParampassed at the call site (hook option orinitiate()option) and its first page failed, the nextrefetch(),fetchNextPage(), poll, or invalidation used the endpoint'sinitialPageParaminstead. That value is now stored on the cache entry and reused. Thanks @kkatalz!Docs Updates
There's a new 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
retryoptions combine. It includes a comparison table for people coming from TanStack Query. The Cache Behavior page now focuses on how long data is kept, includingretainForand 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
useQueryStateresult type signature in the docs is now correct (thanks @FullStraing!).What's Changed
api.util.removeQueryDataby @markerikson in Addapi.util.removeQueryData#5632refetchOnFocus/refetchOnReconnect, and return a promise fromprefetchby @markerikson in Add a seconds value forrefetchOnFocus/refetchOnReconnect, and return a promise fromprefetch#5638invalidationBehavior: 'immediately'by @markerikson in Refetch entries invalidated while their request is running underinvalidationBehavior: 'immediately'#5640upsertQueryEntriesfor in-flight fetches by @markerikson in Add options argument toupsertQueryEntriesfor in-flight fetches #5641initiate()results from keeping the settled store state alive by @markerikson in Stopinitiate()results from keeping the settled store state alive #5642initialPageParamon infinite query refetch andfetchNextPageby @kkatalz in fix(toolkit): keep the hook'sinitialPageParamon infinite query refetch andfetchNextPage#5627Full Changelog: v2.15.0...v2.16.0
This discussion was created from the release v2.16.0.
All reactions