# Rendering and loading patterns This file takes the rendering and performance patterns from patterns.dev and decides whether to use each one and which tool implements it. The playbook, [b2c-b2b.md](b2c-b2b.md), holds the details and wins on any conflict. Code-level patterns are in [design-patterns.md](design-patterns.md), and code smells in [refactoring.md](refactoring.md). Names match the source pages under patterns.dev/react/ and patterns.dev/vanilla/. Contents: Rendering patterns · Auth-dependent UI · Time-dependent UI · Loading patterns · Choosing where a part loads ## Rendering patterns Apps render every page on the server for each request and stream it. The server render is the same for every visitor: what depends on the viewer renders in the browser (Auth-dependent UI below). | Pattern | Use | How here | |---|---|---| | Client-side rendering | Auth-dependent pages and parts; other browser-only parts | A page or part whose UI depends on the viewer renders completely in the browser (Auth-dependent UI below). Other parts render in the browser only when [b2c-b2b.md](b2c-b2b.md#data-flow) says so. | | Server-side rendering | Always, for what's the same for every visitor | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). The server render never depends on auth. | | Static rendering | Never | Nothing renders at build time. Keep each request cheap instead (first note below). | | Incremental static generation | Never | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). | | Partial prerendering | Never | It needs Cache Components, which stay off. `` around slow secondary parts gives an early first paint instead; only `noindex` and blocked pages add a `loading.tsx` ([b2c-b2b.md](b2c-b2b.md#rendering)). | | Streaming server-side rendering | Always | Stream every route as [b2c-b2b.md](b2c-b2b.md#rendering) describes, and make sure nothing buffers the response (second note below). | | React Server Components | Default | Keep components on the server. Only interactive leaves get `'use client'` ([b2c-b2b.md](b2c-b2b.md#rendering)). | | Selective hydration | Automatic | Each part that loads on its own already has its own ``, so it hydrates on its own. Never add a `` only to hydrate a section apart: past React's 12,800-byte limit, it writes the boundary's content after the footer ([b2c-b2b.md](b2c-b2b.md#rendering)). | | Progressive hydration | Through Suspense | Suspense boundaries already hydrate in pieces. To delay a part's JavaScript, keep its markup in a Server Component and load its client piece on visibility or interaction. A lazy-hydration library would be outside the stack. | | Islands architecture | Through Server Components | It's unrelated to the island design system; only the name is shared. Server Components with small client leaves give its benefit: only the interactive parts ship JavaScript and hydrate. | | View transitions | Rare, on Next.js 16.3 or later | React's `` with `next/link`'s `transitionTypes`. The App Router ships its own React, so the Next.js version decides: before 16.3 it needs an experimental flag, so wait. Animate only what helps orientation, such as a product image moving into its detail page, and turn it off under `prefers-reduced-motion`. | - Apps render a fresh page for every request ([b2c-b2b.md](b2c-b2b.md#no-server-cache)), so static rendering, incremental static generation, and partial prerendering are not used. When a page is slow, stream its slow secondary parts, fetch independent data in parallel with `Promise.all`, and fix or cache the slow call in the back end. - When a developer calls a section "static", it means server HTML that ships no JavaScript, never build-time rendering. A page's rendering doc writes it as HTML `first flush` with JS `none` ([page-rendering.md](page-rendering.md#vocabulary)). - Streaming works only when nothing between Next.js and the browser buffers the response. Turn buffering off in the reverse proxy and the CDN (for nginx, return `X-Accel-Buffering: no` from `headers()` in `next.config.ts`), or every page waits for its slowest part. - Experimental APIs, such as `unstable_*` exports, canary-only React features, and Next.js `experimental.*` flags, stay unused until they're stable, unless the repo already enables them. `` counts as stable from React 19.3 and Next.js 16.3 (View transitions row). [SKILL.md](../SKILL.md) prefers boring, proven technology. - Many patterns.dev examples use the Pages Router (`getServerSideProps`, `getStaticProps`, `next/head`), APIs removed in React 19, or libraries such as loadable-components and react-window. Take the idea and write the code with this stack's APIs. ## Auth-dependent UI The server render never depends on auth. Every visitor of a URL gets the same server HTML, whether they are a guest, a logged-in member, or a paying member. A page or part is auth-dependent when what it shows changes with who the viewer is: it needs a logged-in user (orders, addresses, settings), it shows a different UI per user type (a guest, a member without a subscription, a member with one), or it shows the viewer's own data (the cart count, a wishlist, recommendations, a member price). Locale, theme, device, and URL parameters aren't auth, so the server may render by them. - Same for every visitor → render it on the server, through "Choosing where a part loads" below. - Depends on the viewer → render it completely in the browser. The server renders only its same-size skeleton: it never reads the session, sends auth cookies, or picks a variant. In the browser, the part's model reads the viewer and the viewer's data, and the part renders its variant. - Render in the browser only the smallest piece that differs. A product page stays on the server and only its membership offer is a browser part. A page renders in the browser as a whole only when all of it depends on the viewer, such as an account page. - Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write the override in the plan. When they make it a lasting rule, record it as a decision ([decisions.md](decisions.md#when-to-record)). Auth-dependent UI rendered on the server needs the auth cookies forwarded and the session refreshed in `proxy.ts` for the whole app, so record that override as a decision even for one page. Why: - The server renders the same thing for millions of mostly logged-out visitors, with no per-user back-end calls, so TTFB stays flat. - The server can't refresh an expired session, because Server Components can't set cookies. A server render that read the session would show a member the guest UI, or fail, whenever the access token expired. In the browser, the HTTP lib refreshes and replays. - One user's data can never reach another user's HTML through a misconfigured CDN or module state. - Search engines crawl as guests, so they never saw auth-dependent UI. SEO loses nothing, as long as the guest variant, which Google's renderer shows after JavaScript runs, is a neutral, same-size UI. Never make it an error message or an empty box, which Google may read as a soft 404. How: - Server requests forward only the cookies the render needs, never the auth cookies ([b2c-b2b.md](b2c-b2b.md#state-and-auth)), so the back end can't personalize a server response by accident. - The browser learns who the viewer is once per load. The `AppShell` calls the auth feature's `restoreSession` action in an effect, and the action moves the auth store's `status` from `'unknown'` to `'guest'` or `'member'` ([code-patterns.md](code-patterns.md#store)). The session endpoint answers a guest with an empty session, not 401, so a guest never starts a refresh or a logout. When the read still fails after the HTTP lib's retries, the action clears the session, so the status becomes `'guest'`, and rethrows; the `AppShell`'s effect passes the error to `handleError`. - An auth-dependent part renders its same-size skeleton while the status is `'unknown'`. That covers the server render and the first browser render, so hydration matches. Never render the guest variant as the placeholder: a member would see it flash, and the layout would shift. - When the part needs the viewer's own data, its model reads it with `useQuery`, enabled only when the status is `'member'`. Never use a server prefetch or `useSuspenseQuery` for it. - Every variant ships in the route's bundle. Make a heavy variant, such as a subscriber's video player, a `next/dynamic` component with a same-size `loading` skeleton, so each visitor downloads only their own. - A page that needs a logged-in user, such as every `(account)` page: the route group's layout wraps its children in the platform's `AuthGuard` (`app/guards/auth-guard/`). This client component renders the page skeleton while the status is `'unknown'`, sends a guest to login with a return URL, and renders the page for a member. The page stays a thin Server Component that resolves the device and passes only URL parameters to its template, and the template's parts load in the browser. That layout's `metadata` export sets `robots: { index: false }`, and each page's `generateMetadata` reads no data: it returns only the generic title in the request's locale ([ui-rules.md](ui-rules.md#metadata-and-viewport)). - An action that changes the viewer, such as login, logout, or a payment, updates the auth store, so every auth-dependent part renders its new variant. It doesn't call `router.refresh()`, because no server-rendered content changed. `platforms//src/features/membership/models/product/use-membership-offer-part.ts`. A guest sees an invitation to log in, a member without a subscription sees the subscription offer, and a subscriber (`user.hasSubscription`) sees their benefit. `types.ts` declares `MembershipOfferVariant = 'pending' | 'guest' | 'member' | 'subscriber'`. ```ts import { useCurrentUser, useViewerStatus } from '../../../../stores/auth'; import type { MembershipOfferVariant } from './types'; export function useMembershipOfferPart(): MembershipOfferVariant { const status = useViewerStatus(); const user = useCurrentUser(); if (status === 'unknown') return 'pending'; if (status === 'guest') return 'guest'; return user?.hasSubscription ? 'subscriber' : 'member'; } ``` `apps//src/app/(shop)/product/[id]/organisms/membership-offer/MembershipOffer.tsx`. The product template, a Server Component, renders `` beside the server-rendered product summary. The server and the first browser render both show the skeleton. The part reads no data of its own, so it needs no `PartBoundary`; a variant that queries data gets one. ```tsx 'use client'; import { useMembershipOfferPart } from '@project//features/membership'; import { GuestOffer } from './components/guest-offer'; import { MemberOffer } from './components/member-offer'; import { MembershipOfferSkeleton } from './components/membership-offer-skeleton'; import { SubscriberOffer } from './components/subscriber-offer'; export function MembershipOffer() { const variant = useMembershipOfferPart(); if (variant === 'pending') return ; if (variant === 'guest') return ; if (variant === 'member') return ; return ; } ``` ## Time-dependent UI A part whose output depends on the current time, such as a sale countdown or an open-now badge, can't render its time on the server. The server's clock and the browser's differ, so the hydration render wouldn't match the server HTML. React then throws error #418, renders the nearest `` (or the whole root) again in the browser, and reports an error on every view. - The server renders the facts that stay true, next to the prices: the sale's end time and the branch's opening hours. Crawlers index these facts, and they match the JSON-LD. The ticking digits are never indexable content. - Format absolute dates on the server for everything the server renders, with every option pinned, and pass the text down: Node's and the browser's ICU data can format the same date differently. A browser-only part, whose server HTML is its skeleton, such as an account page's order list, formats its dates in the browser with `formatDateTime`. The countdown formats only its digits, with a fixed digit map, not `Intl`. - The current time comes from `useClock` in `packages/tools/src/use-clock/`: the epoch second or minute, or `null` on the server and in the hydration render. So both renders show the same-size skeleton, and one render right after hydration shows the time, with no mismatch. - Never read `Date.now()` or `new Date()` while a client component renders, and never hide a clock with `suppressHydrationWarning`: it reaches one level deep and leaves the server's stale text on screen. Never leave out `useSyncExternalStore`'s server snapshot to make a part browser-only: the server render fails, so the nearest `` ships only its fallback and the browser reports error #419 on every view. With no `` above it, as for a section in an indexable page's first flush, the page answers 500 with `noindex`. - One ticker serves every time-dependent part on the page, so React renders them all in one commit per tick. It ticks on each second boundary and reads `Date.now()` on every tick instead of counting ticks. It stops while the page is hidden and catches up at once when the page shows again, because browsers throttle or freeze timers in hidden tabs. Never give a component its own `setInterval`. - A part that changes at most once a minute, such as an open-now badge, calls `useClock('minute')` and renders once a minute. - Use one countdown per sale window: a rail whose offers end together shows one countdown in its header, not one per card. - At zero, the countdown shows its ended label and announces it once. Nothing refreshes or fetches: every open tab reaches zero in the same second, and each `router.refresh()` is a full server render. Cart and checkout price on the server, and the next page load renders without the sale. - The countdown's `endsAt`, the `dateTime` of its label's `