GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — fix(react-query): resolve hydration mismatch in SSR with prefetched queries by joseph0926 · Pull Request #9572 · TanStack/query Conversation
|
WalkthroughAdds non‑mutating server‑view snapshot methods to QueryObserver and QueriesObserver, switches useBaseQuery/useQueries to use those server snapshots for React.useSyncExternalStore during SSR/hydration, and adds extensive SSR hydration tests covering pending, fetching, error, mixed, and concurrency scenarios. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as React Component
participant H as useBaseQuery / useQueries
participant O as QueryObserver(s)
participant QC as QueryCache
C->>H: render()
H->>O: create/attach observer(s)
H->>H: useSyncExternalStore(subscribe, getServerSnapshot)
H->>O: getServerResult()
O->>QC: read query state (dataUpdatedAt, fetchStatus)
alt dataUpdatedAt == 0 (hydrated)
rect rgba(230,240,255,0.6)
Note right of O: return synthetic server view\n(status: "pending", data masked, isPending: true)
end
O-->>H: serverResult (pending-like)
else
O-->>H: currentResult (unchanged)
end
H-->>C: snapshot for render
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Assessment against linked issues
Out-of-scope changes
Suggested reviewers
✨ Finishing Touches
🧪 Generate unit tests
Comment |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
View your CI Pipeline Execution ↗ for commit 253cb40
☁️ Nx Cloud last updated this comment at |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
packages/react-query/src/useBaseQuery.ts (1)
111-113: Optionally harden against version skew between @tanstack/react-query and @tanstack/query-coreIf a consumer upgrades react-query without upgrading query-core,
observer.getServerResultmay not exist at runtime. A small runtime fallback guards against that without affecting current behavior.Apply this diff:
), () => observer.getCurrentResult(), - () => observer.getServerResult(), + () => + // Guard against version skew where older query-core doesn't have getServerResult + (observer as any).getServerResult + ? (observer as any).getServerResult() + : observer.getCurrentResult(), )packages/query-core/src/queryObserver.ts (2)
274-287: Consider normalizing “pending” snapshot flags for full internal consistencyWhen returning a synthetic pending result,
isFetched/isFetchedAfterMountcould still reflect “fetched” from the spread. While likely harmless for SSR, explicitly setting them tofalsewould avoid mixed semantics (“pending but fetched”).Apply this diff:
const pendingResult: QueryObserverResult<TData, TError> = { ...currentResult, status: 'pending', isPending: true, isSuccess: false, isError: false, isLoading: currentResult.fetchStatus === 'fetching', isInitialLoading: currentResult.fetchStatus === 'fetching', data: undefined, error: null, isLoadingError: false, isRefetchError: false, isPlaceholderData: false, + // Normalize fetched flags in the synthetic pending server snapshot + isFetched: false, + isFetchedAfterMount: false, } as QueryObserverResult<TData, TError>
267-269: Add a short JSDoc explaining server snapshot semanticsA brief doc comment will clarify why
dataUpdatedAt === 0is treated as hydrated and why we synthesize a pending result.Apply this diff:
- getServerResult(): QueryObserverResult<TData, TError> { + /** + * Returns a "server-view" snapshot for useSyncExternalStore during SSR. + * If the observer has hydrated client data (dataUpdatedAt === 0) but the server + * should render a pending UI, synthesize a pending result; otherwise, return the current result. + */ + getServerResult(): QueryObserverResult<TData, TError> {packages/query-core/src/__tests__/queryObserver.test.tsx (1)
1498-1523: Deduplicate “mark as hydrated” setup with a small helperMultiple tests inline the same mutation of
dataUpdatedAtandfetchStatus. A helper will reduce repetition and make intent clearer.An example helper to insert right after the “SSR Hydration” describe:
describe('SSR Hydration', () => { + const markHydrated = ( + qc: QueryClient, + key: ReturnType<typeof queryKey>, + data: unknown, + fetchStatus: 'idle' | 'fetching' = 'idle', + ) => { + qc.setQueryData(key, data) + const cache = qc.getQueryCache().find({ queryKey: key }) + if (cache) { + cache.state.dataUpdatedAt = 0 + cache.state.fetchStatus = fetchStatus + } + }Then, for example:
- queryClient.setQueryData(key, { amount: 10 }) - const cache = queryClient.getQueryCache().find({ queryKey: key }) - if (cache) { - cache.state.dataUpdatedAt = 0 - cache.state.fetchStatus = 'idle' - } + markHydrated(queryClient, key, { amount: 10 }, 'idle')
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/__tests__/queryObserver.test.tsx (1 hunks)packages/query-core/src/queryObserver.ts (1 hunks)packages/react-query/src/useBaseQuery.ts (1 hunks)packages/query-core/src/types.ts (1)
QueryObserverResult(899-904)
packages/query-core/src/queriesObserver.ts (1)
observer(254-260)
packages/query-core/src/queriesObserver.ts (1)
observer(254-260)packages/query-core/src/queryObserver.ts (1)
QueryObserver(39-765)
packages/react-query/src/useBaseQuery.ts (1)
112-113: Switching server snapshot to getServerResult fixes hydration mismatch — LGTMThis is the right hook for SSR to align the server snapshot with server-rendered HTML under hydration. No behavior changes for client snapshots.
packages/query-core/src/queryObserver.ts (1)
267-294: Well-scoped server snapshot that models hydrated data as pending — LGTMNon-mutating, minimal, and conditionally applied only under the hydrated-success state (
dataUpdatedAt === 0). Keepspromiseintact and mirrors fetchStatus for loading flags. This aligns withuseSyncExternalStore’s SSR needs.packages/query-core/src/__tests__/queryObserver.test.tsx (1)
1498-1671: Solid coverage of hydration cases and server/client snapshot divergence — LGTMThe tests clearly demonstrate the mismatch and validate the pending server snapshot across idle/fetching/error paths, plus divergence from client snapshots.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for looking into this 🙌
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| status: 'pending', | ||
| isPending: true, | ||
| isSuccess: false, | ||
| isError: false, | ||
| isLoading: currentResult.fetchStatus === 'fetching', | ||
| isInitialLoading: currentResult.fetchStatus === 'fetching', | ||
| data: undefined, | ||
| error: null, | ||
| isLoadingError: false, | ||
| isRefetchError: false, | ||
| isPlaceholderData: false, |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
how did you come up with this list of fields to change? For example, why aren’t fields like isFetched or isStale being re-set?
I’m wondering how we can make sure to keep this list in-sync if we add new properties to QueryObserverResult...
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thank you for your feedback!
In conclusion, the criteria for selecting the specified fields was “only change fields that directly affect SSR hydration inconsistencies.”
I believe that intentionally maintaining the currentResult value for the remaining fields will be beneficial during subsequent maintenance processes.
However, based on coderabbitai's feedback, I realized that I had overlooked isRefetching, so I added it.
Since the status is fixed as pending, I added it to explicitly state that refetching is not possible.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| currentResult.status === 'success' && | ||
| this.#currentQuery.state.dataUpdatedAt === 0 | ||
| ) { | ||
| const pendingResult: QueryObserverResult<TData, TError> = { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
should this be of type QueryObserverPendingResult to make sure we’re at least always in-sync with what this type guarantees ?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thank you for pointing out the type > QueryObserverPendingResult, which I had overlooked.
I agree that applying this will improve type stability.
However, since currentResult must be of type QueryObserverResult, I handled it as a union.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
packages/query-core/src/queryObserver.ts (1)
277-288: Avoid brittle “whitelist” of overridden fields; centralize pending server result construction.Manually overriding a subset of properties is easy to get out of sync with
QueryObserverResultas new fields are added (e.g.,isFetched,isRefetchingwas already missed). Consider extracting a small helper to construct a coherent pending server snapshot fromcurrentResultandthis.#currentQuery.state.fetchStatus, which sets all invariants in one place and is typed asQueryObserverPendingResult.I can draft a
private toServerPendingResult(...)helper to keep this maintainable if helpful.
packages/query-core/src/queryObserver.ts (1)
268-271: Simplify return type: QueryObserverPendingResult is already part of QueryObserverResult.
QueryObserverPendingResultis a constituent ofQueryObserverResult, so the explicit union is redundant. Keeping the return type as justQueryObserverResult<TData, TError>reduces noise.- getServerResult(): - | QueryObserverPendingResult<TData, TError> - | QueryObserverResult<TData, TError> { + getServerResult(): QueryObserverResult<TData, TError> {
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/queryObserver.ts (2 hunks)packages/query-core/src/types.ts (2)
QueryObserverPendingResult(797-810)QueryObserverResult(899-904)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| getServerResult(): | ||
| | QueryObserverPendingResult<TData, TError> | ||
| | QueryObserverResult<TData, TError> { | ||
| const currentResult = this.#currentResult | ||
|
|
||
| const isHydratedData = | ||
| currentResult.status === 'success' && | ||
| this.#currentQuery.state.dataUpdatedAt === 0 | ||
|
|
||
| if (isHydratedData) { | ||
| return { | ||
| ...currentResult, | ||
| status: 'pending' as const, | ||
| isPending: true, | ||
| isSuccess: false, | ||
| data: undefined, | ||
| isLoading: currentResult.fetchStatus === 'fetching', | ||
| isInitialLoading: currentResult.fetchStatus === 'fetching', | ||
| isPlaceholderData: false, | ||
| } | ||
| } | ||
|
|
||
| return currentResult | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix inconsistent flags for pending server snapshot (isRefetching, error flags, fetched flags).
When transforming a hydrated success result into a pending server snapshot, we spread currentResult and override a few fields. This leaves inconsistencies:
fetchStatus === 'fetching', currentResult.isRefetching was true (because success + fetching), but a pending result must have isRefetching: false (as computed in createResult: isRefetching = isFetching && !isPending).isError: false, error: null, isLoadingError: false, isRefetchError: false, and it’s safer to mark isFetched/isFetchedAfterMount as false to avoid mixed semantics leaking from the success snapshot.Recommend explicitly overriding these to match QueryObserverPendingResult invariants and make the branch type-safe.
Apply this diff inside getServerResult:
if (isHydratedData) {
- return {
- ...currentResult,
- status: 'pending' as const,
- isPending: true,
- isSuccess: false,
- data: undefined,
- isLoading: currentResult.fetchStatus === 'fetching',
- isInitialLoading: currentResult.fetchStatus === 'fetching',
- isPlaceholderData: false,
- }
+ return {
+ ...currentResult,
+ status: 'pending' as const,
+ isPending: true,
+ isSuccess: false,
+ // pending invariants
+ isError: false,
+ error: null,
+ isLoadingError: false,
+ isRefetchError: false,
+ // data is not available for pending
+ data: undefined,
+ // compute loading flags from fetchStatus
+ isLoading: currentResult.fetchStatus === 'fetching',
+ isInitialLoading: currentResult.fetchStatus === 'fetching',
+ // pending cannot be "refetching"
+ isRefetching: false,
+ // do not report placeholder data
+ isPlaceholderData: false,
+ // avoid leaking fetched flags from the success snapshot
+ isFetched: false,
+ isFetchedAfterMount: false,
+ } as QueryObserverPendingResult<TData, TError>
}In packages/query-core/src/queryObserver.ts around lines 268 to 291, when
converting a hydrated success result into a pending server snapshot we currently
spread currentResult but leave several flags inconsistent; explicitly override
the following fields to match QueryObserverPendingResult invariants: set
isRefetching to false, isError to false, error to null, isLoadingError to false,
isRefetchError to false, isFetched to false, and isFetchedAfterMount to false
(retain the existing overrides for
status/isPending/isSuccess/data/isLoading/isInitialLoading/isPlaceholderData).
Ensure these fields are explicitly assigned in the returned object so the
pending snapshot has consistent semantics and is type-safe.
💡 Verification agent
Add test coverage for isRefetching and fetched flags in server snapshot.
To prevent regressions, assert in tests that:
getServerResult() for hydrated data sets isRefetching === false even if fetchStatus === 'fetching'.isFetched === false and isFetchedAfterMount === false.[offer_assistance]
If missing, I can provide a focused test case to assert these invariants.
🏁 Script executed:
#!/bin/bash # Locate existing tests around getServerResult and hydration rg -n -C3 "getServerResult|server snapshot|hydration" --type=ts --type=tsx # Check if isRefetching/isFetched assertions exist rg -n -C2 "isRefetching|isFetchedAfterMount|isFetched" packages/query-core/src/__tests__/queryObserver.test.tsx
Length of output: 218
🏁 Script executed:
#!/bin/bash # Retry pattern search without relying on --type (tsx not recognized) rg -n -C3 "getServerResult|server snapshot|hydration" -g '*.ts' -g '*.tsx' rg -n -C2 "isRefetching|isFetchedAfterMount|isFetched" -g '*.ts' -g '*.tsx'
Length of output: 120039
Add missing assertions for isRefetching, isFetched, and isFetchedAfterMount in server snapshot tests
The existing hydration tests in packages/query-core/src/__tests__/queryObserver.test.tsx verify status, data, and fetchStatus, but don’t cover these derived flags. To prevent regressions, extend the tests under the Solution with getServerResult block:
• After the “should return pending state for hydrated data” test (around line 1530), add:
expect(serverResult.isFetched).toBe(false) expect(serverResult.isFetchedAfterMount).toBe(false) expect(serverResult.isRefetching).toBe(false)
• After the “should handle fetching state during hydration” test (around line 1575), also assert:
expect(serverResult.isFetched).toBe(false) expect(serverResult.isFetchedAfterMount).toBe(false) expect(serverResult.isRefetching).toBe(false)
This will ensure that hydrated snapshots never report fetched or refetching states on the server.
In packages/query-core/src/queryObserver.ts around lines 268 to 291: the server
result produced for hydrated data is missing corresponding unit-test assertions;
update the tests in packages/query-core/src/__tests__/queryObserver.test.tsx
(after the "should return pending state for hydrated data" test near line ~1530
and after the "should handle fetching state during hydration" test near line
~1575) to add assertions that serverResult.isFetched is false,
serverResult.isFetchedAfterMount is false, and serverResult.isRefetching is
false so hydrated server snapshots never report fetched or refetching states.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
packages/query-core/src/queryObserver.ts (2)
277-293: Pending server snapshot leaks fetched flags; align with pending invariants.When masking a hydrated success as pending,
isFetched/isFetchedAfterMountmay still reflect the success snapshot due to the spread. Explicitly reset them tofalseto avoid mixed semantics. Optionally, cast the object toQueryObserverPendingResultfor stronger type guarantees.Apply this diff within the pending branch:
if (isHydratedData) { return { ...currentResult, status: 'pending' as const, isPending: true, isSuccess: false, isError: false, error: null, isLoadingError: false, isRefetchError: false, data: undefined, isRefetching: false, isLoading: currentResult.fetchStatus === 'fetching', isInitialLoading: currentResult.fetchStatus === 'fetching', isPlaceholderData: false, + // avoid leaking "fetched" semantics from the success snapshot + isFetched: false, + isFetchedAfterMount: false, - } + } as QueryObserverPendingResult<TData, TError> }
277-293: Add test assertions for fetched/refetch flags in server snapshot.To prevent regressions, extend the SSR/hydration tests to assert:
serverResult.isFetched === falseserverResult.isFetchedAfterMount === falseserverResult.isRefetching === falseThis ensures the pending server snapshot never exposes “fetched” or “refetching” semantics.
packages/query-core/src/queryObserver.ts (1)
273-276: Sentinel usage confirmed, no unintended zero-timestamps detected
- dataUpdatedAt === 0 only appears as the default initial value in tests and is never reset to 0 elsewhere in your runtime code.
- The
isHydratedDatacheck inpackages/query-core/src/queryObserver.ts:273–276therefore correctly identifies only “fresh” hydration cases.- No other code paths or hydration routines assign
dataUpdatedAt = 0post-dehydration.Nitpick (optional): if you prefer to avoid sprinkling this magic number, you could extract a small helper (e.g.
isHydrated(result)) to centralize the sentinel logic.
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/queryObserver.ts (2 hunks)packages/query-core/src/types.ts (2)
QueryObserverPendingResult(797-810)QueryObserverResult(899-904)
packages/query-core/src/queryObserver.ts (2)
26-26: LGTM: type-only import forQueryObserverPendingResult.Using
import typekeeps this out of runtime bundles and is consistent with surrounding imports.
268-271: Great addition: dedicated server snapshot API for useSyncExternalStore.Providing a server-specific snapshot via
getServerResultcleanly separates SSR vs. client snapshots and addresses the hydration mismatch root cause without mutating observer state.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@ ## main #9572 +/- ## =========================================== + Coverage 45.50% 59.84% +14.33% =========================================== Files 209 138 -71 Lines 8377 5625 -2752 Branches 1897 1520 -377 =========================================== - Hits 3812 3366 -446 + Misses 4118 1957 -2161 + Partials 447 302 -145 🚀 New features to boost your workflow:
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I’m not an expert here so I’ll wait for @Ephem to jump in but the way I see it, the |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Hmm, I understand what you're saying. My PR currently checks the status of currentResult at runtime and changes it dynamically, so there is a possibility of inconsistency. The Context approach you suggested preserves the value rather than transforming it, which aligns more closely with React's philosophy. I'm also curious about @Ephem final opinion. For now, I see two paths forward
For now, I will wait for @Ephem response and refactor this PR using the Context method. +++
In other words, the “actual pending state created by the server” that we want to put into Context has never actually existed, has it? The server only knows the “success” state from start to finish, and the “pending” state we desire is merely our wish for how it should appear. Therefore, the Context approach ultimately // Not “preservation” but still “creation/transformation” const serverSnapshot = { status: ‘pending’, // artificially created data: undefined, // hiding the actual data } This is an artificially created state being placed into the Context, not preserving the actual server state. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I added comprehensive test cases to verify the issues you raised and obtained the following results. Test 1 Test 2 Test 3 // Before isLoading: currentResult.fetchStatus === ‘fetching’, // After isLoading: queryState.fetchStatus === ‘fetching’, This change ensures that the real-time fetch status is reflected even during concurrent operations. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
packages/query-core/src/__tests__/queryObserver.test.tsx (4)
1503-1508: Avoid mutatingquery.statedirectly; usequery.setStateto keep invariants and notifications intactThese tests directly mutate
cache.state.{dataUpdatedAt,fetchStatus}. This bypassesQuery’s state machinery and can make tests brittle against internal changes (e.g., observers not being notified, internal derived fields not recomputed). Prefercache.setState(...).Example fix for Lines 1503–1508:
- if (cache) { - cache.state.dataUpdatedAt = 0 - cache.state.fetchStatus = 'idle' - } + if (cache) { + cache.setState({ dataUpdatedAt: 0, fetchStatus: 'idle' }) + }Similarly adjust Lines 1562–1567:
- if (cache) { - cache.state.dataUpdatedAt = 0 - cache.state.fetchStatus = 'fetching' - } + if (cache) { + cache.setState({ dataUpdatedAt: 0, fetchStatus: 'fetching' }) + }Lines 1586–1590:
- if (cache) { - cache.state.dataUpdatedAt = Date.now() - } + if (cache) { + cache.setState({ dataUpdatedAt: Date.now() }) + }Lines 1712–1717:
- if (cache) { - cache.state.dataUpdatedAt = 0 - cache.state.fetchStatus = 'fetching' - } + if (cache) { + cache.setState({ dataUpdatedAt: 0, fetchStatus: 'fetching' }) + }Lines 1740–1745:
- if (cache) { - cache.state.dataUpdatedAt = 0 - cache.state.fetchStatus = 'idle' - } + if (cache) { + cache.setState({ dataUpdatedAt: 0, fetchStatus: 'idle' }) + }Also applies to: 1562-1567, 1586-1590, 1712-1717, 1740-1745
1501-1501: Clarify test title to reflect what is assertedThis test doesn’t actually demonstrate a hydration “mismatch”; it asserts the client result is “success”. Consider renaming to make intent explicit:
- test('should demonstrate hydration mismatch issue (before fix)', () => { + test('client snapshot with hydrated data is success (illustrates mismatch risk pre-fix)', () => {
1680-1685: Reconsider the “future-proof status” test usingstatus: 'idle' as anyInjecting an out-of-contract status via
as anycouples the test to speculation about future versions and may confuse readers because it asserts that data can exist with an "idle" status. If the goal is to document thatgetServerResultonly masks whenstatus === 'success', make that explicit instead, or mark this as a documentation-style test with a clear comment.
- Option A: Drop the test to avoid validating undefined behavior.
- Option B: Keep it, but add a prominent comment explaining it asserts current, intentional masking criteria.
1656-1669: Optional: Add an end-to-end React test inpackages/react-queryto exerciseuseSyncExternalStoresnapshot parityThis unit test checks the two snapshots via
getCurrentResultandgetServerResult, which is good. For higher confidence, consider adding an integration test inpackages/react-querythat mounts a tiny component usinguseBaseQueryand verifies that the server snapshot (from uSESgetServerSnapshot) matches the HTML and that hydration does not mismatch when client data resolves.Happy to help draft that test if desired.
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/__tests__/queryObserver.test.tsx (1 hunks)packages/query-core/src/queryObserver.ts (2 hunks)packages/query-core/src/queriesObserver.ts (1)
observer(254-260)packages/query-core/src/queryObserver.ts (1)
QueryObserver(40-770)packages/query-core/src/utils.ts (1)
sleep(355-359)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| cache.state.dataUpdatedAt = Date.now() | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
Use a non-zero constant (or set system time) to avoid flakiness with fake timers
Under fake timers, Date.now() may be 0 unless you set the system time. That would unintentionally mark this as “hydrated” (dataUpdatedAt === 0), causing getServerResult to mask the result and fail the “non-hydrated” expectations.
Minimal, deterministic fix:
- cache.state.dataUpdatedAt = Date.now() + cache.setState({ dataUpdatedAt: 1 })
Alternatively, set the mocked clock first:
vi.setSystemTime(1) cache.setState({ dataUpdatedAt: Date.now() })
🏁 Script executed:
#!/bin/bash # Locate usages of dataUpdatedAt to see surrounding test logic rg -n "dataUpdatedAt" -C3 packages/query-core/src/__tests__/queryObserver.test.tsx # Find direct Date.now() calls in the test file rg -n "Date.now" -C3 packages/query-core/src/__tests__/queryObserver.test.tsx # Check for any mocked clock setup or system time manipulation rg -n "setSystemTime" -C3 packages/query-core/src/__tests__/queryObserver.test.tsx # Search for fake-timer setup (vi.useFakeTimers or jest.useFakeTimers) rg -nP "useFakeTimers|fakeTimers" -C3 packages/query-core/src/__tests__/queryObserver.test.tsx
Length of output: 3741
Use a non-zero constant for dataUpdatedAt to avoid flakiness under fake timers
Under vi.useFakeTimers(), Date.now() returns 0 unless you explicitly advance the clock—making your “fresh” timestamp indistinguishable from the unhydrated state. Update the assignment in packages/query-core/src/__tests__/queryObserver.test.tsx to use a non-zero literal (or advance the fake clock first):
• Minimal, consistent with other direct state mutations:
- cache.state.dataUpdatedAt = Date.now() + cache.state.dataUpdatedAt = 1
• Alternative (advance the fake clock, then read):
vi.setSystemTime(1) cache.state.dataUpdatedAt = Date.now()
In packages/query-core/src/__tests__/queryObserver.test.tsx around lines
1589-1590, the test sets cache.state.dataUpdatedAt = Date.now() while using
vi.useFakeTimers(), which makes Date.now() return 0 and causes flakiness; change
the assignment to use a non-zero literal (e.g. set dataUpdatedAt to 1) or
advance the fake timers first by calling vi.setSystemTime(1) and then assign
Date.now() so the "fresh" timestamp is non-zero and consistent under fake
timers.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@Ephem said he might have time this week to look into it, so let’s wait for his feedback |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I’d like to share a few additional findings regarding this issue
Below are links to reproduction code for both scenarios. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…lt for pending state
|
Initially, i used the spread operator to only explicitly modify the fields that needed to be changed while preserving the rest. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
packages/query-core/src/queryObserver.ts (1)
263-305: Solid server snapshot; small cleanups for clarity and reuse.Compute
fetchStatus/isFetchingonce and add a brief JSDoc to document SSR semantics. This reduces repetition and aids future maintenance.- getServerResult(): + /** + * Return a server-stable snapshot for useSyncExternalStore. + * If hydrated-success data is detected (dataUpdatedAt === 0), + * synthesize a pending result so SSR HTML matches client hydration. + */ + getServerResult(): @@ - const currentResult = this.getCurrentResult() + const currentResult = this.getCurrentResult() + const queryState = this.#currentQuery.state + const fetchStatus = queryState.fetchStatus + const isFetching = fetchStatus === 'fetching' @@ - const pendingResult: QueryObserverPendingResult<TData, TError> = { + const pendingResult: QueryObserverPendingResult<TData, TError> = { status: 'pending', - fetchStatus: this.#currentQuery.state.fetchStatus, + fetchStatus, isPending: true, isSuccess: false, isError: false, - isLoading: this.#currentQuery.state.fetchStatus === 'fetching', - isInitialLoading: this.#currentQuery.state.fetchStatus === 'fetching', - isFetching: this.#currentQuery.state.fetchStatus === 'fetching', + isLoading: isFetching, + isInitialLoading: isFetching, + isFetching, isRefetching: false, data: undefined, dataUpdatedAt: 0, error: null, errorUpdatedAt: 0, errorUpdateCount: 0, failureCount: 0, failureReason: null, isLoadingError: false, isRefetchError: false, isFetched: false, isFetchedAfterMount: false, - isPaused: this.#currentQuery.state.fetchStatus === 'paused', + isPaused: fetchStatus === 'paused', isPlaceholderData: false, isStale: currentResult.isStale, refetch: currentResult.refetch, promise: currentResult.promise, isEnabled: currentResult.isEnabled, }
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/queryObserver.ts (2 hunks)packages/query-core/src/types.ts (2)
QueryObserverPendingResult(797-810)QueryObserverResult(899-904)
packages/query-core/src/queryObserver.ts (1)
26-26: LGTM: type-only import is correct.Brings
QueryObserverPendingResultin as a type without runtime impact.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
It appears that useQueries has the same hydration issue. I've added getServerResult() to QueriesObserver which seems to fix it, along with relevant tests. Would appreciate confirmation that this approach makes sense. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
packages/query-core/src/queriesObserver.ts (1)
186-189: Add JSDoc to clarify SSR-only semantics and allocationDocument that this returns a new array and is intended for use as the server snapshot for useSyncExternalStore to avoid future regressions.
Apply:
+ /** + * Returns the server-side snapshot for all observers. + * Intended for React.useSyncExternalStore's getServerSnapshot during SSR/hydration. + * Note: returns a new array each call. + */ getServerResult(): Array<QueryObserverResult> { return this.#observers.map((observer) => observer.getServerResult()) }packages/query-core/src/__tests__/queriesObserver.test.tsx (3)
351-393: Rename the “before fix” test for clarityThe title suggests pre-fix behavior even though this lives post-fix. Rename to avoid confusion.
- test('should demonstrate hydration mismatch issue with multiple queries (before fix)', () => { + test('should demonstrate state divergence between server snapshot and client result for hydrated queries', () => {
405-413: Factor out a helper to mark queries as “hydrated”Directly mutating cache.state is repeated and brittle. Centralize it to reduce duplication and ease future changes.
Add near the top of the file:
function markHydrated( qc: QueryClient, key: unknown[], fetchStatus: 'idle' | 'fetching' = 'idle', ) { const q = qc.getQueryCache().find({ queryKey: key }) if (q) { q.state.dataUpdatedAt = 0 q.state.fetchStatus = fetchStatus } }Then replace blocks like:
- if (cache1) { - cache1.state.dataUpdatedAt = 0 - cache1.state.fetchStatus = 'idle' - } + markHydrated(queryClient, key1, 'idle')Also applies to: 459-467, 498-506
395-447: Add a test for combine() behavior under SSR snapshotsTo cover the public combine API, add a case where combine is provided and verify server vs client snapshots don’t cause mismatches.
I can draft a test that uses combine to join two results and asserts server snapshot stays pending while the returned hook data remains consistent.
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/__tests__/queriesObserver.test.tsx (1 hunks)packages/query-core/src/queriesObserver.ts (1 hunks)packages/react-query/src/useQueries.ts (1 hunks)packages/query-core/src/types.ts (1)
QueryObserverResult(899-904)
packages/query-core/src/queriesObserver.ts (2)
observer(258-264)QueriesObserver(35-281)
packages/query-core/src/queriesObserver.ts (1)
observer(258-264)
packages/react-query/src/useQueries.ts (1)
278-279: LGTM: useSyncExternalStore now uses server snapshot from QueriesObserver.getServerResultThis aligns the server snapshot with the observer’s SSR view and should resolve the hydration mismatch for prefetched queries.
packages/query-core/src/__tests__/queriesObserver.test.tsx (1)
351-529: No duplicate “SSR Hydration” test suites detected.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
packages/query-core/src/__tests__/queriesObserver.test.tsx (5)
363-370: Avoid direct mutation of Query.state; centralize via helper (preferably using setState) and DRY the tests.Directly writing
query.state.*is brittle and bypasses invariants. Also, the repeated mutation code increases maintenance cost.Option A (preferred): use the internal
setStateto keep invariants and notifications correct, wrapped in a helper to avoid repetition:@@ - describe('SSR Hydration', () => { + describe('SSR Hydration', () => { + const markHydrated = (key: unknown[], fetchStatus: 'idle' | 'fetching' = 'idle') => { + const q = queryClient.getQueryCache().find({ queryKey: key }) + expect(q).toBeDefined() + // keep internal invariants + q!.setState((s: any) => ({ ...s, dataUpdatedAt: 0, fetchStatus })) + }Then replace the inline mutations, e.g.:
- if (cache1) { - cache1.state.dataUpdatedAt = 0 - cache1.state.fetchStatus = 'idle' - } - if (cache2) { - cache2.state.dataUpdatedAt = 0 - cache2.state.fetchStatus = 'idle' - } + markHydrated(key1, 'idle') + markHydrated(key2, 'idle')Repeat similarly for the other occurrences (ranges above).
Option B (lighter change): keep the mutation but still centralize it for readability:
const pretendHydrated = (key: unknown[], status: 'idle' | 'fetching' = 'idle') => { const q = queryClient.getQueryCache().find({ queryKey: key }) if (q) { q.state.dataUpdatedAt = 0 q.state.fetchStatus = status } }Also applies to: 405-412, 459-466, 499-505, 541-547, 611-613
360-362: Rename variables for clarity: they are Queries, not Caches.
cache1/cache2areQueryinstances. Considerquery1/query2orq1/q2to avoid confusion withQueryCache.Also applies to: 402-404, 456-458, 495-497, 537-539, 609-610
377-391: Strengthen “Hydration Mismatch Problem” by asserting the server snapshot too.You demonstrate client “success” but don’t assert the corresponding server “pending” snapshot, which better illustrates the divergence you’re documenting.
const clientResults = observer.getCurrentResult() + const serverResults = observer.getServerResult() + expect(serverResults[0]).toMatchObject({ status: 'pending', data: undefined }) + expect(serverResults[1]).toMatchObject({ status: 'pending', data: undefined }) + expect(clientResults[0]).toMatchObject({ status: 'success', data: { amount: 10 }, isLoading: false, isPending: false, })
514-519: Assert isFetching alongside isLoading to validate fetch semantics.Given
fetchStatus: 'fetching',isFetchingshould be true. Asserting it guards against regressions in derived flags.expect(serverResults[0]).toMatchObject({ status: 'pending', fetchStatus: 'fetching', isLoading: true, + isFetching: true, isPending: true, })
589-603: Also assert that the combine function was invoked.You spy on
combineResultsbut don’t verify it was called. A quick assertion tightens coverage ofgetOptimisticResult+ server snapshots.const combined = getCombined(serverResults) + expect(combineResults).toHaveBeenCalledTimes(1) expect(combined).toEqual({ totalAmount: 0, allSuccess: false, allPending: true, })
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/__tests__/queriesObserver.test.tsx (1 hunks)packages/query-core/src/queriesObserver.ts (2)
observer(258-264)QueriesObserver(35-281)packages/query-core/src/types.ts (1)
QueryObserverResult(899-904)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
…shot environments
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
packages/query-core/src/__tests__/queriesObserver.test.tsx (1)
470-478: Flakiness fix acknowledged: replaced Date.now() with sentinel.Using
dataUpdatedAt = 1under fake timers avoids theDate.now() === 0pitfall. Good resolution.
packages/query-core/src/__tests__/queriesObserver.test.tsx (4)
380-380: Unify language in comments.Replace the Korean inline comment with an English equivalent for consistency across the codebase.
Apply:
- // 서버와 클라이언트의 차이를 명확히 보여줌 + // Explicitly illustrate the server vs. client difference
601-608: Avoid unused binding for tuple destructuring.Prefer elision to
_to satisfy linters withnoUnusedLocals.Apply:
- const [_, getCombined] = observer.getOptimisticResult( + const [, getCombined] = observer.getOptimisticResult(
416-423: DRY the repeated “mark hydrated/non-hydrated” setup.Factor a tiny helper to reduce repetition and keep sentinel usage consistent.
Example:
+ const setHydrationState = ( + q: any | undefined, + hydrated: boolean, + fetchStatus: 'idle' | 'fetching' = 'idle', + ) => { + if (q) { + q.state.dataUpdatedAt = hydrated ? 0 : 1 + q.state.fetchStatus = fetchStatus + } + }Then replace occurrences like:
- if (query1) { - query1.state.dataUpdatedAt = 0 - query1.state.fetchStatus = 'idle' - } + setHydrationState(query1, true, 'idle')Also applies to: 552-559, 510-517
617-617: Clarify test title or scenario.This test mixes “hydrated” (key1) with “missing” (key2 has no data). Rename for clarity, or set key2 to a non-hydrated success (
setQueryData(...); dataUpdatedAt = 1) if you intended “non-hydrated success.”- test('should handle combine with mixed hydrated and non-hydrated queries', () => { + test('should handle combine with hydrated and missing queries', () => {
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/__tests__/queriesObserver.test.tsx (1 hunks)packages/query-core/src/queriesObserver.ts (2)
observer(258-264)QueriesObserver(35-281)packages/query-core/src/types.ts (1)
QueryObserverResult(899-904)
packages/query-core/src/__tests__/queriesObserver.test.tsx (1)
351-359: Solid SSR hydration coverage added — aligns with getServerResult semantics.The suite captures hydrated, mixed, fetching, and combine cases and validates server/client snapshot divergence correctly.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
packages/query-core/src/queryObserver.ts (2)
265-267: Add a brief JSDoc to lock intentDocument the SSR contract to reduce future regressions and clarify the dataUpdatedAt === 0 sentinel.
Apply above the method:
+ /** + * Server snapshot for useSyncExternalStore during SSR/hydration. + * If the query is a hydrated success (dataUpdatedAt === 0), synthesize a + * pending-style result so the client hydrates against the server-rendered HTML. + * Otherwise, return the current result. + */ getServerResult():
270-273: Avoid torn reads: capture state/fetchStatus oncethis.#currentQuery.state is read multiple times; it can change between reads under concurrent updates. Snapshot it once to make the pending result internally consistent.
- const currentResult = this.getCurrentResult() + const currentResult = this.getCurrentResult() + const state = this.#currentQuery.state + const fetchStatus = state.fetchStatus @@ - currentResult.status === 'success' && - this.#currentQuery.state.dataUpdatedAt === 0 + currentResult.status === 'success' && + state.dataUpdatedAt === 0 @@ - fetchStatus: this.#currentQuery.state.fetchStatus, + fetchStatus, @@ - isLoading: this.#currentQuery.state.fetchStatus === 'fetching', - isInitialLoading: this.#currentQuery.state.fetchStatus === 'fetching', - isFetching: this.#currentQuery.state.fetchStatus === 'fetching', + isLoading: fetchStatus === 'fetching', + isInitialLoading: fetchStatus === 'fetching', + isFetching: fetchStatus === 'fetching', @@ - isPaused: this.#currentQuery.state.fetchStatus === 'paused', + isPaused: fetchStatus === 'paused',Also applies to: 276-283, 295-296
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
packages/query-core/src/queryObserver.ts (2 hunks)packages/query-core/src/types.ts (2)
QueryObserverPendingResult(797-810)QueryObserverResult(899-904)
packages/query-core/src/queryObserver.ts (3)
28-32: LGTM: precise type importBringing in QueryObserverPendingResult keeps the API surface strongly typed for the new server snapshot path.
265-267: API shape is soundUnion return type for getServerResult correctly reflects pending vs. regular snapshots.
274-301: Pending invariants are consistently enforcedGood call explicitly overriding all pending invariants (data/error flags, fetched flags, refetching). Using query state for fetchStatus aligns with concurrent correctness.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const pendingResult: QueryObserverPendingResult<TData, TError> = { | ||
| status: 'pending', | ||
| fetchStatus: this.#currentQuery.state.fetchStatus, | ||
| isPending: true, | ||
| isSuccess: false, | ||
| isError: false, | ||
| isLoading: this.#currentQuery.state.fetchStatus === 'fetching', | ||
| isInitialLoading: this.#currentQuery.state.fetchStatus === 'fetching', | ||
| isFetching: this.#currentQuery.state.fetchStatus === 'fetching', | ||
| isRefetching: false, | ||
| data: undefined, | ||
| dataUpdatedAt: 0, | ||
| error: null, | ||
| errorUpdatedAt: 0, | ||
| errorUpdateCount: 0, | ||
| failureCount: 0, | ||
| failureReason: null, | ||
| isLoadingError: false, | ||
| isRefetchError: false, | ||
| isFetched: false, | ||
| isFetchedAfterMount: false, | ||
| isPaused: this.#currentQuery.state.fetchStatus === 'paused', | ||
| isPlaceholderData: false, | ||
| isStale: currentResult.isStale, | ||
| refetch: currentResult.refetch, | ||
| promise: currentResult.promise, | ||
| isEnabled: currentResult.isEnabled, | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
Verify tests assert the key pending invariants
Please confirm tests cover isRefetching === false, isFetched === false, and isFetchedAfterMount === false for hydrated snapshots (and optionally that failureCount/reset fields are as intended).
Run:
🏁 Script executed:
#!/bin/bash # Assert server-snapshot tests exist rg -n -C2 "getServerResult|server snapshot|SSR|hydration" packages/query-core/src/__tests__ -g '*.ts' -g '*.tsx' # Check for invariants on hydrated server results rg -n -C2 "isRefetching\W*toBe\((false|0)\)|isFetched\W*toBe\((false|0)\)|isFetchedAfterMount\W*toBe\((false|0)\)" \ packages/query-core/src/__tests__ -g '*.ts' -g '*.tsx'
Length of output: 46044
Add missing invariant assertions in SSR hydration tests
packages/query-core/src/__tests__/queryObserver.test.tsx under the “Solution with getServerResult” SSR Hydration suite, add:
expect(serverResult.isFetched).toBe(false) expect(serverResult.isFetchedAfterMount).toBe(false)
failureCount, errorUpdatedAt, etc., reset to 0/null as intended.In packages/query-core/src/queryObserver.ts around lines 274 to 301, update the
SSR hydration tests (packages/query-core/src/__tests__/queryObserver.test.tsx
under the “Solution with getServerResult” suite) to include invariant assertions
that serverResult properties reset after hydration: add
expect(serverResult.isFetched).toBe(false) and
expect(serverResult.isFetchedAfterMount).toBe(false); optionally also assert
that numeric/timestamp and error fields are reset (failureCount === 0,
errorUpdatedAt === 0, error === null, failureReason === null) to ensure the
pendingResult shape matches the expected initial state.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Hey, is there any update on this? Did @Ephem ever take a look at it? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
I'm unsure if my PR addresses the core issue and is structurally sound, so I intended to close it and make corrections if his feedback indicated it was wrong. However, since I haven't received feedback yet, I've closed it for now. DeepL로 번역함 (https://dee.pl/apps) |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Sorry this has taken so long, life has been incredibly hectic so had to step away from OSS for a bit to stay sane. 😄 Despite what I said in the issue, I'm not sure if hard-coding the pending state is the right approach here. What we'd ideally do is snapshot a immutable version of the initial payload that gets passed to I've scheduled time on Friday to look deeper into this! |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I attempted to store immutable data and utilize it, but structural changes would be required, which seems to go beyond the scope of this PR and is beyond my capabilities, so I stopped trying. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
WIll do, I really appreciate you taking time to try to fix this! it might be a good fix while we work on the bigger structural changes, I'll reopen it in that case. Even if not, I'm sure some of those tests will come in useful, so thank you. 😄 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Hi, I think the issue I am experiencing is this exact thing, where a prefetch on the server first SSRs a "loading" state because of query.isLoading. Then, at time of hydration the data is already available and renders the new tree with the correct loaded state. Has there been any progress on this? Any workarounds until this is fixed? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
Hydration error using loading state of useQuery when prefetching useSyncExternalStore should have a correct/frozen getServerSnapshot
There was an error while loading. Please reload this page.