Sometimes I have come across when someone pairs Suspense
and a key
prop, even the official tutorial of Next.js has it:
<Suspense key={query + currentPage} fallback={<InvoicesTableSkeleton />}>
<Table query={query} currentPage={currentPage} />
</Suspense>
I've used this approach with keys on regular components (to reset state), but I wasn't sure why it was used with Suspense
. Can someone provide more info?
It appears if a render is happening within a transition Suspense
will not show its fallback even if any of its children block on a promise.
This is highlighted in this article:
Normally we'd expect a Suspense boundary to show its fallback if any of its children block on a promise during a re-render. But if the re-render is happening within a transition, the Suspense boundary will actually keep its existing content displayed rather than showing its fallback again
You can encounter this for example if you use router.push
from useRouter
of next/naviagion
- in that case it appears Next.js is updating our app within a transition.
More info
Official docs also have info on this however they reset the top component with a key which likely contains the Suspense
boundary:
During a Transition, React will avoid hiding already revealed content. However, if you navigate to a route with different parameters, you might want to tell React it is different content. You can express this with a key:
<ProfilePage key={queryParams.id} />
Imagine you’re navigating within a user’s profile page, and something suspends. If that update is wrapped in a Transition, it will not trigger the fallback for already visible content. That’s the expected behavior.
However, now imagine you’re navigating between two different user profiles. In that case, it makes sense to show the fallback. For example, one user’s timeline is different content from another user’s timeline. By specifying a
key
, you ensure that React treats different users’ profiles as different components, and resets the Suspense boundaries during navigation. Suspense-integrated routers should do this automatically.