153 lines
14 KiB
Markdown
153 lines
14 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 · Loading patterns · Choosing where a part loads
|
|
|
|
## Rendering patterns
|
|
|
|
Apps render every page on the server for each request and stream it.
|
|
|
|
| Pattern | Use | How here |
|
|
|---|---|---|
|
|
| Client-side rendering | Parts only | A page renders only its browser-only parts in the browser ([b2c-b2b.md](b2c-b2b.md#data-flow)). |
|
|
| Server-side rendering | Always | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
|
|
| 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.
|
|
|
|
## 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. Every match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (1), makes its thumbnails a small client leaf (2), and loads its zoom viewer only when the user opens it (3 and 4). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow).
|
|
|
|
1. 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.
|
|
2. 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.
|
|
3. It's personal, 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).
|
|
4. 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`.
|