Skip to main content
Version: 10.x

Suspense (Experimental)

info
  • useSuspenseQuery & useSuspenseInfiniteQuery are experimental features
  • Ensure you're on the latest version of React
  • If you use suspense with tRPC's automatic SSR in Next.js, the full page will crash on the server if a query fails, even if you have an <ErrorBoundary />

Usage

tip

useSuspenseQuery & useSuspenseInfiniteQuery both return a [data, query]-tuple, to make it easy to directly use your data and renaming the variable to something descriptive

useSuspenseQuery()

tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
 
function PostView() {
const [post, postQuery] = trpc.post.byId.useSuspenseQuery({ id: '1' });
const post: { id: string; title: string; }
 
return <>{/* ... */}</>;
}
tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
 
function PostView() {
const [post, postQuery] = trpc.post.byId.useSuspenseQuery({ id: '1' });
const post: { id: string; title: string; }
 
return <>{/* ... */}</>;
}

useSuspenseInfiniteQuery()

tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
function PostView() {
const [pages, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.nextCursor;
},
},
);
const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
allPostsQuery;
return <>{/* ... */}</>;
}
tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
function PostView() {
const [pages, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.nextCursor;
},
},
);
const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
allPostsQuery;
return <>{/* ... */}</>;
}