229 lines
23 KiB
Markdown
229 lines
23 KiB
Markdown
# 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 · 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. `loading.tsx` and `<Suspense>` give an early first paint instead ([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 | Give each independent part its own `<Suspense>` boundary, so it hydrates on its own ([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 `<ViewTransition>` 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 parts, fetch independent data in parallel with `Promise.all`, and fix or cache the slow call in the back end.
|
|
- 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. `<ViewTransition>` 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.
|
|
|
|
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. `generateMetadata` reads no data: it returns a generic title and `robots: { index: false }`.
|
|
- 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/<platform>/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/<app>/src/app/(shop)/product/[id]/organisms/membership-offer/MembershipOffer.tsx`. The product template, a Server Component, renders `<MembershipOffer />` 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/<platform>/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 <MembershipOfferSkeleton />;
|
|
if (variant === 'guest') return <GuestOffer />;
|
|
if (variant === 'member') return <MemberOffer />;
|
|
return <SubscriberOffer />;
|
|
}
|
|
```
|
|
|
|
## Loading patterns
|
|
|
|
The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Record each route's deferred parts and what triggers them in the plan (the PR description).
|
|
|
|
| Pattern | Use | How here |
|
|
|---|---|---|
|
|
| Static import | Default | A static import in a `'use client'` file ships to the browser. Put heavy modules behind a dynamic import. |
|
|
| Dynamic import | `next/dynamic` in a client component | Select the named export: `.then((mod) => mod.Chart)`. For code that isn't a component, use `await import()` in the event handler. In a `Record` map from key to component inside a client component, such as a CMS block type, make each heavy entry a `next/dynamic` component, so the map doesn't pull every entry into the route's bundle. A map in a Server Component needs nothing: only the client entries it renders ship. |
|
|
| Import on visibility | Widgets below the fold | Wrap the lazy component in island's `LoadOnVisible` primitive (code below). |
|
|
| Import on interaction | Heavy widgets and embeds | Start the download on `pointerenter` or `focus`, and render on click. A static facade (patterns.dev's word for a placeholder, unrelated to the GoF Facade in design-patterns.md) stands in for video, maps, and chat until then (code below). |
|
|
| Route-based splitting | Automatic | The App Router splits each route segment. |
|
|
| Bundle splitting | Automatic | Steer it with small client boundaries and dynamic imports rather than the bundler's chunk settings, and check each route against its budget. |
|
|
| Tree shaking | Always | Use named re-exports without `export *`, subpath imports, and `sideEffects` in every package ([project-structure.md](project-structure.md#exports-and-tree-shaking)). |
|
|
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache only through prefetch, because a service worker is outside the stack and needs approval. Lazy-load the rest with route splitting and dynamic imports. |
|
|
| Preload | LCP image, critical font | Preload what [b2c-b2b.md](ui-rules.md#images-fonts-and-css) lists, and use React 19's resource functions for other origins and late files (notes below). |
|
|
| Prefetch | `next/link` default | Keep `next/link`'s default prefetch (notes below). |
|
|
| Loading sequence | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. |
|
|
| Third-party loading | After hydration | Load from `packages/integrations` with `next/script` and `afterInteractive` or `lazyOnload` ([b2c-b2b.md](b2c-b2b.md#bundle-and-code-splitting)). `@next/third-parties` is outside the stack, and the `worker` strategy is experimental, doesn't work in the App Router, and needs Partytown, which is outside the stack. |
|
|
| List virtualization | Long interactive lists, with approval | Paginate on the server and try `content-visibility` first. The library is outside the stack (notes below). |
|
|
| Compressing JavaScript | CDN or proxy | Serve Brotli, with gzip as fallback, from the CDN or the reverse proxy. Budgets are measured gzipped. When the proxy compresses, set `compress: false` in `next.config.ts`. |
|
|
|
|
- On these dynamic routes, `next/link`'s default prefetch stops at the nearest `loading.tsx`, so a click shows the skeleton at once ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). Never set `prefetch={true}`: every link in the viewport would then ask the server for a full render, and the server caches nothing.
|
|
- The LCP image and the critical font follow [b2c-b2b.md](ui-rules.md#images-fonts-and-css). For anything else, use React 19's resource functions from `react-dom`: `preconnect` for an origin the first screen needs, `prefetchDNS` for one it needs later (such as an embed's host), and `preload` for a critical file the HTML references late. Call them during render or in an event handler; React dedupes the tags.
|
|
- Paginate lists on the server first. Give each row of a long, mostly static list a functional utility from island's `styles/utilities.css`, `@utility content-auto-* { content-visibility: auto; contain-intrinsic-size: auto calc(var(--spacing) * --value(integer)); }`, used as `content-auto-16`: off-screen rows skip rendering but stay in the DOM, so find-in-page and screen readers keep working. When an interactive list still renders more than about 200 rows, such as a feed, a log, or a large tree, propose `@tanstack/react-virtual` with the reason and its gzipped size, and add it only after approval ([SKILL.md](../SKILL.md#2-stack)).
|
|
|
|
`packages/island/src/primitives/load-on-visible/LoadOnVisible.tsx`. It shows the fallback until the element comes within the root margin of the viewport, then renders the children inside `<Suspense>` with the same fallback. The primitive doesn't import `next/dynamic`: the caller passes the lazy component as children, and the import starts when the child first renders. A chunk that fails to load reaches the part's own error boundary.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import { Suspense, useEffect, useRef, useState } from 'react';
|
|
import { LOAD_ON_VISIBLE_ROOT_MARGIN } from './constants';
|
|
import type { LoadOnVisibleProps } from './types';
|
|
|
|
export function LoadOnVisible({ children, fallback, rootMargin = LOAD_ON_VISIBLE_ROOT_MARGIN }: LoadOnVisibleProps) {
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
const [isNear, setIsNear] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const element = ref.current;
|
|
if (isNear || !element) return;
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
if (entries.some((entry) => entry.isIntersecting)) setIsNear(true);
|
|
},
|
|
{ rootMargin },
|
|
);
|
|
observer.observe(element);
|
|
return () => observer.disconnect();
|
|
}, [isNear, rootMargin]);
|
|
|
|
return <div ref={ref}>{isNear ? <Suspense fallback={fallback}>{children}</Suspense> : fallback}</div>;
|
|
}
|
|
```
|
|
|
|
The module also has `types.ts` (`LoadOnVisibleProps`: `children`, `fallback`, and an optional `rootMargin`), `constants.ts` (`LOAD_ON_VISIBLE_ROOT_MARGIN = '200px 0px'`), and `index.ts`. It has no `variants.ts`, because it has no styles.
|
|
|
|
`apps/<app>/src/app/(shop)/product/[id]/organisms/price-history/PriceHistory.tsx`. The product template, a Server Component, renders this client leaf below the fold. Call `next/dynamic` in the same client component as `LoadOnVisible`: a client component that a Server Component imports already ships with the route, so wrapping it would defer only its render. Leave out `ssr: false` here, as [b2c-b2b.md](b2c-b2b.md#data-flow) allows: `LoadOnVisible` or the interaction already keeps the child out of the server render, and with `ssr: false` `next/dynamic` adds its own `<Suspense>` with an empty fallback, which would replace the skeleton or the facade. Where the dynamic component renders unconditionally, keep `ssr: false` and pass `loading: () => <SameSizeSkeleton />`, so its boundary never renders blank.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import { LoadOnVisible } from '@project/island/primitives/load-on-visible';
|
|
import dynamic from 'next/dynamic';
|
|
import { PriceHistorySkeleton } from './components/price-history-skeleton';
|
|
import type { PriceHistoryProps } from './types';
|
|
|
|
const PriceHistoryChart = dynamic(() =>
|
|
import('./components/price-history-chart').then((mod) => mod.PriceHistoryChart),
|
|
);
|
|
|
|
export function PriceHistory({ productId }: PriceHistoryProps) {
|
|
return (
|
|
<LoadOnVisible fallback={<PriceHistorySkeleton />}>
|
|
<PriceHistoryChart productId={productId} />
|
|
</LoadOnVisible>
|
|
);
|
|
}
|
|
```
|
|
|
|
`apps/<app>/src/app/(shop)/product/[id]/organisms/product-video/ProductVideo.tsx`. One module-level function holds the import, so the facade's intent events (`pointerenter` and `focus`) start the download before the click, and the dynamic component reuses that download. The click sets state inside a transition: React keeps the facade on screen until the chunk arrives, and `isStarting` drives its loading state. The intent download ignores its own failure; the click retries through `next/dynamic`, and a failure there reaches the part's error boundary. A facade lives with its widget, in a route organism or, for a third-party embed such as chat, in the integration's `components/`.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import dynamic from 'next/dynamic';
|
|
import { useState, useTransition } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { VideoFacade } from './components/video-facade';
|
|
import type { ProductVideoProps } from './types';
|
|
|
|
const loadVideoPlayer = () => import('./components/video-player');
|
|
const VideoPlayer = dynamic(() => loadVideoPlayer().then((mod) => mod.VideoPlayer));
|
|
|
|
export function ProductVideo({ video }: ProductVideoProps) {
|
|
const { t } = useTranslation('catalog');
|
|
const [isPlaying, setIsPlaying] = useState(false);
|
|
const [isStarting, startTransition] = useTransition();
|
|
|
|
if (isPlaying) return <VideoPlayer src={video.url} autoPlay />;
|
|
|
|
return (
|
|
<VideoFacade
|
|
posterUrl={video.posterUrl}
|
|
label={t('product.video.play', { name: video.title })}
|
|
isLoading={isStarting}
|
|
onIntent={() => {
|
|
loadVideoPlayer().catch(() => undefined);
|
|
}}
|
|
onPlay={() => startTransition(() => setIsPlaying(true))}
|
|
/>
|
|
);
|
|
}
|
|
```
|
|
|
|
## Choosing where a part loads
|
|
|
|
Ask about each part of a page in this order. Step 1 decides first, and every later match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (2), makes its thumbnails a small client leaf (3), and loads its zoom viewer only when the user opens it (4 and 5). These are defaults: an explicit request from the developer to render a part on the server or in the browser wins (Auth-dependent UI). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow).
|
|
|
|
1. It depends on the viewer → it renders completely in the browser behind a same-size skeleton, even when search engines or the first paint would want it (Auth-dependent UI). Split off what is the same for every visitor, and ask about that piece from step 2.
|
|
2. Search engines or the first paint need it → a Server Component that reads caches, inside `<Suspense>` with a same-size skeleton when it's slow.
|
|
3. The user interacts with it → only the interactive piece becomes a client leaf, driven by its part model, with server data as props or through query hydration.
|
|
4. It's below the fold or shown only on interaction, and search engines don't need it → a browser-only part: `useQuery` with a skeleton, or `next/dynamic`: with `ssr: false` when it renders unconditionally, without it inside `LoadOnVisible` or behind an interaction (see the `PriceHistory` note).
|
|
5. Its code is heavy, or it's a third party → a dynamic import that starts on visibility or interaction, behind a same-size skeleton or a facade. Third-party scripts use `next/script` with `afterInteractive` or `lazyOnload`.
|
|
|
|
**What keeps a part out of the server HTML.** `'use client'` doesn't, and neither does `<Suspense>`. Client components render to HTML on the server and then hydrate. `<Suspense>` only decides what shows while its children wait: the server streams the fallback, then the children's HTML when they're ready. A child that never suspends renders on the server as if the boundary weren't there, and a `useSuspenseQuery` inside it sends its request from the server. Only these keep a part's real UI out of the server HTML:
|
|
|
|
| Technique | The server HTML holds | Use it for |
|
|
|---|---|---|
|
|
| Output that depends on browser-only state: the auth store's `status` while it's `'unknown'`, or a `useQuery` while it's pending | The skeleton the component returns | Auth-dependent parts (step 1) and data loaded only in the browser (step 4) |
|
|
| `next/dynamic` with `ssr: false` and a same-size `loading` skeleton | The `loading` skeleton | Heavy code that renders at once but the first paint doesn't need (steps 4 and 5) |
|
|
| `LoadOnVisible`, or rendering only after an interaction | The fallback or the facade | Parts below the fold or shown on interaction (steps 4 and 5) |
|
|
|
|
- `ssr: false` throws a bail-out during the server render, so the nearest Suspense boundary sends its fallback. Suspense is how the skip happens, not what causes it.
|
|
- React also falls back to client rendering when a child throws during the server render. That's an error path: never use it to keep a part off the server.
|
|
- Decide what the server HTML must hold, the real UI or a skeleton, then pick the technique. Add `<Suspense>` for streaming and selective hydration, never to move a part to the browser.
|