Next.js SPA patterns

Runnable demos for the Single-Page Applications guide. Each route maps to one section of the guide, so you can read the guide and try the pattern side by side.

The data-fetching examples provide initial data from a Server Component, then let the client library manage browser revalidation.

Getting started

npm install
npm run dev

Open http://localhost:3000. Throttle the browser's network tab to watch the initial data stream into the page.

What each route shows

RouteGuide sectionWhat to look for
/use-contextUsing React's use within a Context ProviderThe layout starts getUser() unawaited and passes the Promise through context; Profile unwraps it with use() and suspends.
/swrSPAs with SWRProvides fallback data, then revalidates in the browser and coordinates an optimistic mutation with a tagged server read.
/swr/[id]SPAs with SWR (scoped to a route segment)params.then() resolves the id inside <Suspense> and provides fallback data before SWR revalidates that product in the browser.
/swr/browser-cache/[id]Browser-only caching with Cache ComponentsSWR fetches the data in the browser while Next.js caches the RSC payload for client navigations.
/react-querySPAs with TanStack QueryProvides initial query data with a tag-coordinated hydration timestamp; optimistic mutations update the same client identity.
/react-query/[id]SPAs with TanStack Query (scoped to a route segment)The product cache contract owns its query key, server tag, and query options; a tagged server read provides the initial query data.
/react-query/browser-cache/[id]Browser-only caching with Cache ComponentsTanStack Query fetches the data in the browser while Next.js caches the RSC payload for client navigations.
/browser-onlyRendering components only in the browserCompares next/dynamic with ssr: false and React's use(browser()) API for components that read window.
/shallow-routingShallow routing on the clientwindow.history.pushState updates ?sort= with no reload; useSearchParams re-sorts the list.
/mutationsMutating data with Server ActionsA to-do list where a Server Action runs as an async reducer via useActionState, and useOptimistic (sharing one reducer with the server) applies each change instantly.

Configuration

The app enables Cache Components and Partial Prefetching. Routes with server-provided data prerender a static shell and stream dynamic data behind <Suspense>.

A note on static export

Static export (output: 'export') is not currently compatible with Cache Components. Because this demo enables Cache Components, it must run with a server. The Server Action in /mutations also requires a server.

Stack