Skip to content
Source
Sign inSign up
TanStack/query

fix(react-query): move away of uSES #8434

ClosedKATT(GitHub profile, opens in a new tab)wants to merge 67 commits intomain fromrefs/pull/8434/headopened View on GitHub

Closes #8384 (I think/hope !?!!?) Closes #8249 too

Refactor @tanstack/react-query to not rely on useSyncExternalStore() as it creates issues in concurrent rendering


I think it works!? I added the repro in examples and I also tried to add a test to make it fail

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query

    2. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    3. View your CI Pipeline Execution ↗ for commit 9797e93a0b6090b5351bf6a07e89deb072125ef6.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded4m 31sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-01-03 14:12:06 UTC

    4. Open in Stackblitz

      More templates

      @tanstack/angular-query-devtools-experimental

      npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@8434

      @tanstack/angular-query-experimental

      npm i https://pkg.pr.new/@tanstack/angular-query-experimental@8434

      @tanstack/eslint-plugin-query

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@8434

      @tanstack/query-broadcast-client-experimental

      npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@8434

      @tanstack/query-async-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@8434

      @tanstack/query-core

      npm i https://pkg.pr.new/@tanstack/query-core@8434

      @tanstack/query-devtools

      npm i https://pkg.pr.new/@tanstack/query-devtools@8434

      @tanstack/query-persist-client-core

      npm i https://pkg.pr.new/@tanstack/query-persist-client-core@8434

      @tanstack/query-sync-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@8434

      @tanstack/react-query

      npm i https://pkg.pr.new/@tanstack/react-query@8434

      @tanstack/react-query-devtools

      npm i https://pkg.pr.new/@tanstack/react-query-devtools@8434

      @tanstack/react-query-next-experimental

      npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@8434

      @tanstack/react-query-persist-client

      npm i https://pkg.pr.new/@tanstack/react-query-persist-client@8434

      @tanstack/solid-query

      npm i https://pkg.pr.new/@tanstack/solid-query@8434

      @tanstack/solid-query-devtools

      npm i https://pkg.pr.new/@tanstack/solid-query-devtools@8434

      @tanstack/solid-query-persist-client

      npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@8434

      @tanstack/svelte-query

      npm i https://pkg.pr.new/@tanstack/svelte-query@8434

      @tanstack/svelte-query-devtools

      npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@8434

      @tanstack/svelte-query-persist-client

      npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@8434

      @tanstack/vue-query

      npm i https://pkg.pr.new/@tanstack/vue-query@8434

      @tanstack/vue-query-devtools

      npm i https://pkg.pr.new/@tanstack/vue-query-devtools@8434

      commit: 9797e93

    5. github-actions[bot](GitHub profile, opens in a new tab) removed labelspackage: query-core

    6. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query-devtools

    7. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query-persist-client

    8. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    9. packages/react-query/src/__tests__/useIsFetching.test.tsx line 57Outdated
      @@ -54,4 +54,3 @@
      5454 await findByText('isFetching: 0')
      5555 })
      5656
      57- it('should not update state while rendering', async () => {

      I'm guessing we should just trust React to optimize re-renders? 🤷

    10. OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
    11. OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
    12. OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
    13. OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
    14. Resolvedby TkDodo
    15. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query-next-experimental

    16. github-actions[bot](GitHub profile, opens in a new tab) removed labelspackage: react-query-next-experimental

    17. packages/react-query/src/__tests__/useQuery.test.tsx line 2488Outdated
      @@ -2485,4 +2486,3 @@
      24852486 expect(queryCache.find({ queryKey: key })!.options.retryDelay).toBe(20)
      24862487 })
      24872488
      2488- it('should batch re-renders', async () => {

      This test doesn't work anymore when we're force rendering

      I'm guessing we just have to trust the concurrency in React to do this in an optimal way?

    18. github-actions[bot](GitHub profile, opens in a new tab) removed labelspackage: react-query-devtools

    19. github-actions[bot](GitHub profile, opens in a new tab) removed labelspackage: react-query-persist-client

    20. Codecov Report

      :x: Patch coverage is 80.00000% with 3 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 46.23%. Comparing base (3bc3147) to head (9797e93). :warning: Report is 796 commits behind head on main.

      Additional details and impacted files

      Impacted file tree graph

      @@           Coverage Diff           @@
      ##             main    #8434   +/-   ##
      =======================================
        Coverage   46.23%   46.23%           
      =======================================
        Files         199      199           
        Lines        7512     7503    -9     
        Branches     1714     1704   -10     
      =======================================
      - Hits         3473     3469    -4     
      - Misses       3664     3672    +8     
      + Partials      375      362   -13     
      ComponentsCoverage Δ
      @tanstack/angular-query-devtools-experimental∅ <ø> (∅)
      @tanstack/angular-query-experimental88.65% <ø> (ø)
      @tanstack/eslint-plugin-query88.22% <ø> (ø)
      @tanstack/query-async-storage-persister43.85% <ø> (ø)
      @tanstack/query-broadcast-client-experimental∅ <ø> (∅)
      @tanstack/query-codemods0.00% <ø> (ø)
      @tanstack/query-core94.57% <0.00%> (ø)
      @tanstack/query-devtools4.78% <ø> (ø)
      @tanstack/query-persist-client-core57.73% <ø> (ø)
      @tanstack/query-sync-storage-persister84.61% <ø> (ø)
      @tanstack/react-query95.60% <92.30%> (+0.06%):arrow_up:
      @tanstack/react-query-devtools10.00% <ø> (ø)
      @tanstack/react-query-next-experimental∅ <ø> (∅)
      @tanstack/react-query-persist-client100.00% <ø> (ø)
      @tanstack/solid-query78.92% <ø> (+0.72%):arrow_up:
      @tanstack/solid-query-devtools∅ <ø> (∅)
      @tanstack/solid-query-persist-client100.00% <ø> (ø)
      @tanstack/svelte-query87.33% <ø> (ø)
      @tanstack/svelte-query-devtools∅ <ø> (∅)
      @tanstack/svelte-query-persist-client100.00% <ø> (ø)
      @tanstack/vue-query71.45% <ø> (ø)
      @tanstack/vue-query-devtools∅ <ø> (∅)
      :rocket: New features to boost your workflow:
      • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
      • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
  • TkDodo reviewed

    Let's please make sure to test this with the reproduction from #8384 to make sure it fixes our issue, and also with the reproduction from #7012 to make sure it doesn't introduce tearing ❤️

    TkDodoreplied on packages/query-core/src/queryObserver.ts line 701

    this is a great improvement 🎉

    OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
    TkDodoreplied on packages/react-query/src/useIsFetching.ts lines 19 to 22

    this could be done without dependency array - updating the ref after every render is fine.

    packages/react-query/src/useMutationState.ts line 59Outdated
    @@ -62,15 +54,6 @@
    62- mutationCache.subscribe(() => {
    63- const nextResult = replaceEqualDeep(
    64- result.current,
    65- getResult(mutationCache, optionsRef.current),
    66- )
    67- if (result.current !== nextResult) {
    68- result.current = nextResult
    69- notifyManager.schedule(onStoreChange)
    70- }
    71- }),
    72- [mutationCache],
    73- ),
    74- () => result.current,
    75- () => result.current,
    76- )!
    54+ const [result, setResult] = React.useState<Array<TResult>>(() =>
    55+ getResult(mutationCache, options),
    56+ )
    57+
    58+ React.useEffect(() => {
    59+ const sub = mutationCache.subscribe(() => {
    TkDodocommented

    one thing that's missing here is calling the setter directly in useEffect, like we do in useBaseQuery and useIsFetching to make sure we do not miss any query updates between creating the observer and subscribing to it.

    I know it's not really possible because the result isn't necessarily a primitive.

    Do you think it would be possible to keep useSyncExternalStore for useMutationState and useIsFetching ?

    I'm not sure if we should keep useSyncExternalStore - it seems to me like something that should be deprecated in React if it by design causes issues as soon as you use startTransition?

    Or maybe it does make sense to use uSES here, idk....

    Reveted them too, 76bfacf for future reference

  • OutdatedResolvedby KATT(GitHub profile, opens in a new tab)
  • packages/react-query/src/__tests__/transition.test.tsx lines 15 to 17
    @@ -0,0 +1,17 @@
    1+/* eslint-disable @typescript-eslint/require-await */
    2+import { act, render, screen } from '@testing-library/react'
    3+import * as React from 'react'
    4+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
    5+import { QueryClientProvider, useQuery } from '..'
    6+import { QueryCache } from '../index'
    7+import { createQueryClient, queryKey, sleep } from './utils'
    8+
    9+const queryCache = new QueryCache()
    10+const queryClient = createQueryClient({
    11+ queryCache,
    12+})
    13+
    14+beforeAll(() => {
    15+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    16+ // @ts-ignore
    17+ global.IS_REACT_ACT_ENVIRONMENT = true
  • .vscode/settings.json lines 1 to 4
    @@ -0,0 +1,4 @@
    1+{
    2+ "editor.defaultFormatter": "esbenp.prettier-vscode",
    3+ "editor.formatOnSave": true
    4+}

    Feel free to remove this, but it helps me as a contributor - I have a bunch of settings in trpc https://github.com/trpc/trpc/tree/next/.vscode

  • packages/react-query/src/useBaseQuery.ts line 120
    @@ -105,7 +99,21 @@
    99+
    100+ // Update result to make sure we did not miss any query updates
    101+ // between creating the observer and subscribing to it.
    102+ observer.updateResult()
    103+
    104+ return unsubscribe
    105+ }, [observer, isRestoring])
    105106
    106107 React.useEffect(() => {
    108+ if (defaultedOptions.experimental_prefetchInRender) {
    109+ return
    110+ }
    107111 // Do not notify on updates because of changes in the options because
    108112 // these changes should already be reflected in the optimistic result.
    109113 observer.setOptions(defaultedOptions, { listeners: false })
    110114 }, [defaultedOptions, observer])
    111115
    116+ if (defaultedOptions.experimental_prefetchInRender) {
    117+ // Do not notify on updates because of changes in the options because
    118+ // these changes should already be reflected in the optimistic result.
    119+ observer.setOptions(defaultedOptions, { listeners: false })

    Setting the options straight away for experimental_prefetchInRender seems to fix it.

    I think the issue I had was some race condition...

    I still have no reliable reproduction though

  • make sure it doesn't introduce tearing

    Unfortunately there's no way to avoid tearing without using uSES (except moving everything onto the react state). But this is fine, it's an acceptable drawback in some situations.

    Side note: maybe it worth introducing a separate hook for that? or a config option for those who doesn't want to have unavoidable tearing?

    But I'm pretty happy with this change, it's a huge improvement and removes some ugly hacks I'm using (like mocking the native impl of the uSES with the uSES-shim to force enable transitions in cost of tearing)

  • The only "blocker" right now is that we haven't yet been able to do a reliable reproduction to the original issue, I wasn't able to reproduce the issue within vite myself

  • TkDodocommented

    I think with all I know as of today, I don’t think it’s likely that we will be going back to useEffect and useState. Instead, exploring concurrent stores sounds more intriguing. If there’s a working ponyfill, I would be very interested in seeing a PR that tries to integrate this in react-query

  • I think with all I know as of today, I don’t think it’s likely that we will be going back to useEffect and useState. Instead, exploring concurrent stores sounds more intriguing. If there’s a working ponyfill, I would be very interested in seeing a PR that tries to integrate this in react-query

    The ponyfill in itself is actually quite small so maybe it can been seen as more of a reference to do something similar, but more integrated, within react-query instead of importing it? (it still involves useState and useEffect ;) )

  • Sorry for spamming, but I'm following the discussions around this closely for my own library. I figure I should share my findings with you, since you need to solve this as well. See bsky thread up until https://bsky.app/profile/ricky.fm/post/3lyyoh3ngfc2g

  • we’re gonna wait for concurrent stores.

  • TkDodo closed this

  • Sign in to join this conversation.