T
TanStack•10mo ago
skilled-lime

Suspense confusion

Given the following:
function App() {
return (
<>
<div>Header</div>
<SuspenseComponent />
<div>Footer</div>
</>
);
}

function SuspenseComponent() {
const { data } = useSuspenseQuery({
queryKey: ['key'],
queryFn: async () => {
await new Promise((res) => setTimeout(res, 5_000));
return Math.random();
},
});

return <Suspense fallback={'Loading...'}>{data}</Suspense>;
}
function App() {
return (
<>
<div>Header</div>
<SuspenseComponent />
<div>Footer</div>
</>
);
}

function SuspenseComponent() {
const { data } = useSuspenseQuery({
queryKey: ['key'],
queryFn: async () => {
await new Promise((res) => setTimeout(res, 5_000));
return Math.random();
},
});

return <Suspense fallback={'Loading...'}>{data}</Suspense>;
}
I expected to initially see Header and Footer and Loading... and then after 5 seconds see the random number, but instead I get a blank screen for 5 seconds and then see everything. I have a reproduction here: https://stackblitz.com/edit/vitejs-vite-sryzjy?file=src%2FApp.tsx Am I fundamentally misunderstanding how useSuspenseQuery works?
Michael Wolfenden
StackBlitz
Vitejs - Vite (forked) - StackBlitz
Next generation frontend tooling. It's fast!
2 Replies
genetic-orange
genetic-orange•10mo ago
more like how suspense works. Suspense must be around the component that suspends. The suspending part is useQuery, so you need:
function App() {
return (
<>
<div>Header</div>
<Suspense fallback={'Loading...'}>
<SuspenseComponent />
</Suspense>
<div>Footer</div>
</>
);
}
function App() {
return (
<>
<div>Header</div>
<Suspense fallback={'Loading...'}>
<SuspenseComponent />
</Suspense>
<div>Footer</div>
</>
);
}
The component istself is then de-coupled from loading states and reads just:
function SuspenseComponent() {
const { data } = useSuspenseQuery({
queryKey: ['key'],
queryFn: async () => {
await new Promise((res) => setTimeout(res, 5_000));
return Math.random();
},
});

return <div>{data}</div>
}
function SuspenseComponent() {
const { data } = useSuspenseQuery({
queryKey: ['key'],
queryFn: async () => {
await new Promise((res) => setTimeout(res, 5_000));
return Math.random();
},
});

return <div>{data}</div>
}
skilled-lime
skilled-limeOP•10mo ago
Ahhhhhh, cheers for the speedy reply @TkDodo 🔮

Did you find this page helpful?