tRPC experimental_defer compatibility with useSuspenseQuery
0 reputation · 22 Sept 2021, 02:51 UTC
0 reputation · 22 Sept 2021, 02:51 UTC
The experimental_defer feature in tRPC v10 allows for the deferral of query execution to optimize initial page loads by delaying specific data fetching until the component mounts.
Current documentation indicates that this functionality is designed to work with standard useQuery hooks. However, there is a known gap regarding its interaction with useSuspenseQuery, which relies on a different execution model for handling asynchronous states during the render phase.
Integrating these two features creates uncertainty regarding how the deferral mechanism handles the suspension lifecycle without triggering hydration mismatches or blocking the initial render.
experimental_defer provide a mechanism to bypass the immediate suspension of useSuspenseQuery?33775 reputation · 22 Sept 2021, 11:00 UTC
1. Does experimental_defer let useSuspenseQuery skip its immediate suspension?
No. The flag only postpones the network request until the component mounts; it does not change React’s Suspense behavior. useSuspenseQuery will still suspend the component until the deferred promise resolves.
2. What happens when a deferred query is executed inside a Suspense boundary?
The boundary shows its fallback until the promise resolves. The request starts after the first render cycle, but the component cannot render until the data arrives, so the initial render is still blocked by Suspense.
Set up a minimal component:
import { trpc } from "@trpc/next";
import { Suspense } from "react";
function User() {
const { data } = trpc.user.get.useSuspenseQuery(undefined, {
experimental_defer: true,
});
return <div>{data.name}</div>;
}
export default function Page() {
return (
<Suspense fallback={<p>Loading user…</p>}>
<User />
</Suspense>
);
}
Run the app. The fallback renders immediately; the network request starts after the first render, and the user data appears once the promise resolves.
For SSR, ensure the server does not defer the same query, or render the component only on the client to avoid hydration mismatches.
useQuery InsteadIf you need the component to render without blocking, switch to useQuery and combine it with experimental_defer. This keeps the UI responsive while the data is fetched in the background.
There is no built‑in way for experimental_defer to bypass the suspension of useSuspenseQuery. They operate independently. Use useQuery or a manual useEffect if you want to avoid the initial suspension.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.