17 KiB
Rendering and loading patterns
This file takes the rendering and performance patterns from patterns.dev and decides, for each project type, whether to use each one and which tool implements it. The playbooks, b2c-b2b.md and admin-panels.md, hold the details and win on any conflict. Code-level patterns are in design-patterns.md, and code smells in 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
B2C/B2B apps render every page on the server for each request and stream it. Admin panels are client-side rendered SPAs, so the server rendering patterns don't apply to them.
| Pattern | B2C/B2B | Admin panel | How here |
|---|---|---|---|
| Client-side rendering | Parts only | Always | A B2C/B2B page renders only its browser-only parts in the browser (b2c-b2b.md). An admin panel renders every screen there, each lazy-loaded behind a skeleton (admin-panels.md). |
| Server-side rendering | Always | Doesn't apply | Render every page fresh for each request, and read data through caches (b2c-b2b.md). |
| Static rendering | Never | Doesn't apply | Nothing renders at build time. Keep each request cheap instead (first note below). |
| Incremental static generation | Never | Doesn't apply | Nothing needs revalidating: after a mutation, router.refresh() renders the page again (b2c-b2b.md). |
| Partial prerendering | Never | Doesn't apply | It needs Cache Components, which stay off. loading.tsx and <Suspense> give an early first paint instead (b2c-b2b.md). |
| Streaming server-side rendering | Always | Doesn't apply | Stream every route as b2c-b2b.md describes, and make sure nothing buffers the response (second note below). |
| React Server Components | Default | Doesn't apply | Keep components on the server. Only interactive leaves get 'use client' (b2c-b2b.md). |
| Selective hydration | Automatic | Doesn't apply | Give each independent part its own <Suspense> boundary, so it hydrates on its own (b2c-b2b.md). |
| Progressive hydration | Through Suspense | Doesn't apply | 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 | Doesn't apply | 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 | Rare | B2C/B2B: 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. Admin panel: TanStack Router's defaultViewTransition or a link's viewTransition option, which call the browser's View Transitions API; don't add React's <ViewTransition> as well. Animate only what helps orientation, such as a product image moving into its detail page, and turn it off under prefers-reduced-motion. |
- B2C/B2B apps render a fresh page for every request (b2c-b2b.md), 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: nofromheaders()innext.config.ts), or every page waits for its slowest part. - Experimental APIs, such as
unstable_*exports, canary-only React features, and Next.jsexperimental.*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 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 and admin-panels.md. Record each route's deferred parts and what triggers them in the plan's research.md (spec-kit.md).
| Pattern | B2C/B2B | Admin panel | How here |
|---|---|---|---|
| Static import | Default | Default | A static import in a 'use client' file ships to the browser, and one reachable from the admin shell (navigation.ts, the AppShell, bootstrap) ships in the shell bundle. Put heavy modules behind a dynamic import. |
| Dynamic import | next/dynamic in a client component |
lazyRouteComponent, React.lazy |
Select the named export: .then((mod) => mod.Chart) for next/dynamic, .then((mod) => ({ default: mod.Chart })) for React.lazy. 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 or React.lazy 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 | Widgets below the fold | Wrap the lazy component in island's LoadOnVisible primitive (code below). |
| Import on interaction | Heavy widgets and embeds | Editors, viewers, modal content | 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 | Every screen | The App Router splits each route segment. Admin routes load their screens with lazyRouteComponent (admin-panels.md). |
| Bundle splitting | Automatic | 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 | Always | Use named re-exports without export *, subpath imports, and sideEffects in every package (project-structure.md). |
| PRPL | Built in | Built in | Preload critical files (next row). Render the route with the streamed server render, or with the admin shell and a skeleton. 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 | Rarely | Preload what b2c-b2b.md lists, and use React 19's resource functions for other origins and late files (notes below). |
| Prefetch | next/link default |
On intent | Keep next/link's default prefetch (notes below). In an admin panel, set defaultPreload: 'intent' on createRouter, and call prefetchQuery on hover (admin-panels.md). |
| Loading sequence | Always | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. An admin panel loads its shell, then the route chunk behind its skeleton, then widgets. |
| Third-party loading | After hydration | After the shell renders | Load from packages/integrations with next/script and afterInteractive or lazyOnload (b2c-b2b.md). In an admin panel, the integration's loader runs in an effect of the AppShell. @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 | Over about 200 rows, with approval | Paginate on the server and try content-visibility first. The library is outside the stack (notes below). |
| Compressing JavaScript | CDN or proxy | CDN | 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 nearestloading.tsx, so a click shows the skeleton at once (b2c-b2b.md). Never setprefetch={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. For anything else, use React 19's resource functions from
react-dom:preconnectfor an origin the first screen needs,prefetchDNSfor one it needs later (such as an embed's host), andpreloadfor 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. Admin page sizes stop at 100, so a paginated table never reaches the virtualization threshold. 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 ascontent-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-virtualwith the reason and its gzipped size, and add it only after approval (SKILL.md).
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. island also serves admin panels, so 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.
'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 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. An admin caller passes a React.lazy component the same way.
'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/. An admin panel builds the component with lazy(() => loadPdfViewer().then((mod) => ({ default: mod.PdfViewer }))).
'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).
B2C/B2B (data details in b2c-b2b.md):
- 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. - 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.
- It's personal, below the fold, or shown only on interaction, and search engines don't need it → a browser-only part:
useQuerywith a skeleton, ornext/dynamic: withssr: falsewhen it renders unconditionally, without it insideLoadOnVisibleor behind an interaction (see thePriceHistorynote). - 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/scriptwithafterInteractiveorlazyOnload.
Admin panel (admin-panels.md); anything not listed loads with its screen:
- A route →
lazyRouteComponentinnavigation/navigation.ts, with a skeleton of the page layout aspendingComponent. - A heavy widget, such as a chart, an editor, a PDF viewer, or a map → a
React.lazycomponent. Below the fold, pass it toLoadOnVisiblewith a same-size skeleton asfallback;LoadOnVisiblesupplies the Suspense boundary. Above the fold, wrap it in its own<Suspense>with that skeleton. Either way, it gets its own error boundary. - Tab or modal content → its lazy component renders on first open. Build that into island's tabs and dialog organisms, and keep a visited tab mounted in
<Activity mode="hidden">so it keeps its state when the user switches away. - Select or autocomplete options → the part model's
useQuerywithenabled: isOpen, searched and paginated on the server.