42 KiB
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, holds the details and wins 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 · 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 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). 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). |
| Partial prerendering | Never | It needs Cache Components, which stay off. <Suspense> around slow secondary parts gives an early first paint instead; only noindex and blocked pages add a loading.tsx (b2c-b2b.md). |
| Streaming server-side rendering | Always | Stream every route as b2c-b2b.md 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). |
| Selective hydration | Automatic | Each part that loads on its own already has its own <Suspense>, so it hydrates on its own. Never add a <Suspense> 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). |
| 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), 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 flushwith JSnone(page-rendering.md). - 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.
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). Auth-dependent UI rendered on the server needs the auth cookies forwarded and the session refreshed in
proxy.tsfor 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), so the back end can't personalize a server response by accident.
- The browser learns who the viewer is once per load. The
AppShellcalls the auth feature'srestoreSessionaction in an effect, and the action moves the auth store'sstatusfrom'unknown'to'guest'or'member'(code-patterns.md). 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; theAppShell's effect passes the error tohandleError. - 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 oruseSuspenseQueryfor it. - Every variant ships in the route's bundle. Make a heavy variant, such as a subscriber's video player, a
next/dynamiccomponent with a same-sizeloadingskeleton, 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'sAuthGuard(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'smetadataexport setsrobots: { index: false }, and each page'sgenerateMetadatareads no data: it returns only the generic title in the request's locale (ui-rules.md). - 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'.
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.
'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 />;
}
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 <Suspense> (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, notIntl. - The current time comes from
useClockinpackages/tools/src/use-clock/: the epoch second or minute, ornullon 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()ornew Date()while a client component renders, and never hide a clock withsuppressHydrationWarning: it reaches one level deep and leaves the server's stale text on screen. Never leave outuseSyncExternalStore's server snapshot to make a part browser-only: the server render fails, so the nearest<Suspense>ships only its fallback and the browser reports error #419 on every view. With no<Suspense>above it, as for a section in an indexable page's first flush, the page answers 500 withnoindex. - 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 ownsetInterval. - 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, thedateTimeof its label's<time>, and the offer'ssaleEndsin the JSON-LD are one payload value: an ISO 8601 date-time with its offset (lib-json-ld.md). The back end stops sending a sale when the sale ends, so a fresh render never marks up a past date. - Accessibility: the digits have
role="timer"andaria-labelledbypointing at the visible label, and noaria-live, so screen readers never speak every second. Ticking digits are auto-updating content (WCAG 2.2.2, Level A), so users need a control that stops or hides them, or that sets how often they update. Digits that show hours and minutes only still update by themselves, and need the control too; a page that shows only the end time needs none. Record the product's choice as a DDR (decisions.md). TheCountdownbelow has no such control: build the one the DDR picks before a page renders the digits. - The skeleton and the digits take the same box: use
tabular-nums, and check that the font has thetnumfeature. The skeleton is the digits' glyph pattern in transparent text over the skeleton color, and the ended label shares the digits' grid cell.
packages/tools/src/use-clock/use-clock.ts, a generic hook (design-patterns.md). types.ts declares ClockUnit = 'second' | 'minute', and index.ts exports useClock and ClockUnit.
import { useSyncExternalStore } from 'react';
import type { ClockUnit } from './types';
// One ticker for every time-dependent part on the page, so React renders them all in one commit per tick.
// React calls subscribe and the client snapshots only in the browser, and getServerSnapshot on the server,
// so this module state never holds a request's data.
const listeners = new Set<() => void>();
let second = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const readSecond = () => Math.floor(Date.now() / 1000);
function tick(): void {
second = readSecond();
listeners.forEach((listener) => listener());
// Land on the next second boundary, and read the time again on every tick, so drift never adds up.
timer = setTimeout(tick, 1000 - (Date.now() % 1000));
}
function stop(): void {
clearTimeout(timer);
timer = undefined;
}
// Browsers throttle or freeze timers in hidden tabs: stop while hidden, and catch up at once when visible.
// visibilitychange also fires when the page enters and leaves the back/forward cache.
function onVisibilityChange(): void {
stop();
if (document.visibilityState === 'visible') tick();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
if (listeners.size === 1) {
document.addEventListener('visibilitychange', onVisibilityChange);
onVisibilityChange();
}
return () => {
listeners.delete(listener);
if (listeners.size > 0) return;
stop();
document.removeEventListener('visibilitychange', onVisibilityChange);
};
}
// A number that changes once per tick, as useSyncExternalStore needs. With no ticker running
// (before the first subscribe, or while the page is hidden), it reads the time itself.
function getSecond(): number {
if (timer === undefined) second = readSecond();
return second;
}
const getMinute = () => Math.floor(getSecond() / 60);
// The server render and the hydration render both get null, so they match.
const getServerSnapshot = () => null;
// The current epoch second or minute, or null on the server and in the hydration render.
export function useClock(unit: ClockUnit): number | null {
return useSyncExternalStore(subscribe, unit === 'minute' ? getMinute : getSecond, getServerSnapshot);
}
packages/island/src/atoms/countdown/: an atom with plain props that draws one visual unit. Its variants.ts gives countdownVariants the base inline-flex items-center gap-2 tabular-nums and the sizes sm (text-sm) and md (text-base, the default). index.ts exports Countdown, CountdownDigits, CountdownProps, countdownVariants, and COUNTDOWN_MAX_MS. Use it only when the sale ends less than COUNTDOWN_MAX_MS (99 hours) after the request, so the hours keep two digits and fit the skeleton's box, even on a browser clock an hour behind the server's. The Server Component that renders it decides, and a later sale shows its end-time label alone. A Server Component may read the clock, because its output never hydrates.
types.ts
import type { VariantProps } from 'class-variance-authority';
import type { ReactNode } from 'react';
import type { countdownVariants } from './variants';
export type CountdownDigits = 'latn' | 'arabext';
export type CountdownProps = VariantProps<typeof countdownVariants> & {
endsAt: string; // ISO 8601 with its offset, the same value as the offer's saleEnds: '2026-10-21T23:59:59+03:30'
label: ReactNode; // rendered on the server: the text and a <time dateTime={endsAt}> formatted on the server
endedLabel: string; // replaces the digits at zero: 'This offer has ended'
digits?: CountdownDigits; // default 'latn'
className?: string;
};
constants.ts
import type { CountdownDigits } from './types';
// A fixed map, not Intl: Node's and the browser's ICU data can differ, and the skeleton must match.
export const COUNTDOWN_DIGITS: Record<CountdownDigits, string> = {
latn: '0123456789',
arabext: '۰۱۲۳۴۵۶۷۸۹',
};
// The skeleton has the digits' glyph pattern, so the skeleton and the digits take the same box.
export const COUNTDOWN_PLACEHOLDER = '00:00:00';
// Under 100 hours the hours keep two digits; 99 leaves an hour for a browser clock that runs behind.
export const COUNTDOWN_MAX_MS = 99 * 60 * 60 * 1000;
Countdown.tsx
'use client';
import { useClock } from '@project/tools/use-clock';
import { useId } from 'react';
import { cn } from '../../tools/cn';
import { COUNTDOWN_DIGITS, COUNTDOWN_PLACEHOLDER } from './constants';
import type { CountdownDigits, CountdownProps } from './types';
import { countdownVariants } from './variants';
const pad = (value: number) => String(value).padStart(2, '0');
function formatLeft(seconds: number): string {
return `${pad(Math.floor(seconds / 3600))}:${pad(Math.floor(seconds / 60) % 60)}:${pad(seconds % 60)}`;
}
function toDigits(text: string, digits: CountdownDigits): string {
return text.replace(/\d/g, (digit) => COUNTDOWN_DIGITS[digits][Number(digit)]);
}
export function Countdown({ endsAt, label, endedLabel, digits = 'latn', size, className }: CountdownProps) {
const labelId = useId();
// null on the server and in the hydration render: both show the skeleton, so they match.
const now = useClock('second');
const left = now === null ? null : Math.max(0, Math.floor(Date.parse(endsAt) / 1000) - now);
const hasEnded = left === 0;
return (
<span className={cn(countdownVariants({ size }), className)}>
<span id={labelId}>{label}</span>
{/* The digits and the ended label share one grid cell, so neither change shifts the layout. */}
<span className="grid">
<span
role="timer"
aria-labelledby={labelId}
aria-hidden={left === null || hasEnded || undefined}
dir="ltr"
className={cn(
'col-start-1 row-start-1',
left === null && 'rounded-sm bg-surface-muted text-transparent',
hasEnded && 'invisible',
)}
>
{toDigits(left === null ? COUNTDOWN_PLACEHOLDER : formatLeft(left), digits)}
</span>
<span aria-hidden className={cn('col-start-1 row-start-1', !hasEnded && 'invisible')}>
{endedLabel}
</span>
</span>
{/* Announces the end once; the ticking digits are never announced. */}
<span role="status" className="sr-only">
{hasEnded ? endedLabel : null}
</span>
</span>
);
}
packages/tools/src/format-date-time/format-date-time.ts, the date formatter that design-patterns.md's Flyweight row puts in packages/tools. Server Components call it for everything the server renders; a client component calls it only in a browser-only part, whose server HTML is its skeleton.
const formatters = new Map<string, Intl.DateTimeFormat>();
// One formatter per locale and time zone (Flyweight), built from the app's constants, never from user input.
// The locale tag pins the calendar and the digits, such as 'fa-IR-u-ca-persian-nu-arabext', so the text
// never depends on the runtime's ICU defaults or its TZ variable.
export function formatDateTime(iso: string, locale: string, timeZone: string): string {
const key = `${locale} ${timeZone}`;
let formatter = formatters.get(key);
if (!formatter) {
formatter = new Intl.DateTimeFormat(locale, { timeZone, dateStyle: 'medium', timeStyle: 'short' });
formatters.set(key, formatter);
}
return formatter.format(new Date(iso));
}
apps/<app>/src/app/(shop)/product/[id]/organisms/product-price/ProductPrice.tsx, a Server Component, renders the facts and the countdown. PriceLines renders the sale price and the struck-through price in the first flush. getServerI18n stands for the app's per-request i18next setup in src/i18n/, and DATE_LOCALE and STORE_TIME_ZONE for the app's constants, such as 'fa-IR-u-ca-persian-nu-arabext' and 'Asia/Tehran'; match their real names.
import { COUNTDOWN_MAX_MS, Countdown } from '@project/island/atoms/countdown';
import { formatDateTime } from '@project/tools/format-date-time';
import { DATE_LOCALE, STORE_TIME_ZONE } from '../../../../../../constants';
import { getServerI18n } from '../../../../../../i18n';
import { PriceLines } from './components/price-lines';
import type { ProductPriceProps } from './types';
export async function ProductPrice({ price, locale }: ProductPriceProps) {
const i18n = await getServerI18n(locale);
const endsAt = price.discountEndsAt;
const label = endsAt && (
<>
{i18n.t('catalog:price.discount-ends')}{' '}
<time dateTime={endsAt}>{formatDateTime(endsAt, DATE_LOCALE, STORE_TIME_ZONE)}</time>
</>
);
return (
<div>
<PriceLines price={price} />
{endsAt &&
// A Server Component may read the clock: its output never hydrates.
(Date.parse(endsAt) - Date.now() < COUNTDOWN_MAX_MS ? (
<Countdown endsAt={endsAt} label={label} endedLabel={i18n.t('catalog:price.discount-ended')} digits="arabext" />
) : (
<p>{label}</p>
))}
</div>
);
}
The product page's JSON-LD builder passes the same price.discountEndsAt as the offer's saleEnds (lib-json-ld.md). The lib writes it as the offer's validThrough, and its date as priceValidUntil, and listPrice becomes the StrikethroughPrice. So the markup, the visible end time, and the countdown come from one value in one request.
An open-now badge, packages/island/src/atoms/open-status/OpenStatus.tsx, reads the same clock by the minute. The branch's payload gives its opening periods for the next 7 days as ISO instants (OpenPeriod = { opensAt: string; closesAt: string }), so the browser does no time-zone math. Its variants give it a minimum width and three statuses, pending (transparent text over the skeleton color), open, and closed, so the skeleton and either label take the same box. The hours table stays in the first flush, formatted on the server.
'use client';
import { useClock } from '@project/tools/use-clock';
import { cn } from '../../tools/cn';
import type { OpenStatusProps } from './types';
import { openStatusVariants } from './variants';
export function OpenStatus({ periods, openLabel, closedLabel, className }: OpenStatusProps) {
const minute = useClock('minute');
if (minute === null) {
return (
<span aria-hidden className={cn(openStatusVariants({ status: 'pending' }), className)}>
{openLabel}
</span>
);
}
const now = minute * 60_000;
const isOpen = periods.some(({ opensAt, closesAt }) => Date.parse(opensAt) <= now && now < Date.parse(closesAt));
return (
<span className={cn(openStatusVariants({ status: isOpen ? 'open' : 'closed' }), className)}>
{isOpen ? openLabel : closedLabel}
</span>
);
}
Loading patterns
The budgets these patterns protect are in b2c-b2b.md. Record each page's deferred sections and what triggers them in the page's rendering doc (page-rendering.md).
| 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). |
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache through prefetch, and for repeat visits through the pwa lib's service worker, which keeps JS, CSS, fonts, and the icon sprite and never pages (lib-pwa.md). Lazy-load the rest with route splitting and dynamic imports. |
| Preload | LCP image, critical font | Preload what ui-rules.md 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). @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 nearestloading.tsx, so a click shows the skeleton at once (b2c-b2b.md). An indexable page has noloading.tsx, so a link to it prefetches nothing, and the current page stays until the new one arrives: make every link to an indexable page the platform'sNavLink, which shows a pending hint inside the clicked link (code below). 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 ui-rules.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. 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. 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.
'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/.
'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))}
/>
);
}
platforms/<platform>/src/app/navigation/components/nav-link/NavLink.tsx, the link to every indexable page. It renders next/link's <Link> with a pending hint inside, because useLinkStatus reads only the nearest <Link>: inside a plain <a> it always reports idle, and a plain <a> loads the whole document. It is navigation UI in the platform rather than in island, because island imports no next/link, as LoadOnVisible imports no next/dynamic. types.ts declares NavLinkProps = ComponentProps<typeof Link>, and index.ts exports NavLink and its props type.
'use client';
import { cn } from '@project/island/tools/cn';
import Link from 'next/link';
import { LinkPendingHint } from './components/link-pending-hint';
import type { NavLinkProps } from './types';
export function NavLink({ className, children, ...props }: NavLinkProps) {
return (
<Link {...props} className={cn('relative', className)}>
{children}
<LinkPendingHint />
</Link>
);
}
components/link-pending-hint/LinkPendingHint.tsx, private to NavLink. The hint always renders at a fixed size and changes only its opacity, after 100 ms, so it never shifts the layout, and a fast navigation shows nothing.
'use client';
import { useLinkStatus } from 'next/link';
import { linkPendingHintVariants } from './variants';
export function LinkPendingHint() {
const { pending } = useLinkStatus();
return <span aria-hidden className={linkPendingHintVariants({ pending })} />;
}
components/link-pending-hint/variants.ts
import { cva } from 'class-variance-authority';
export const linkPendingHintVariants = cva(
'pointer-events-none absolute inset-x-0 bottom-0 h-0.5 bg-action-primary transition-opacity',
{
variants: {
pending: {
true: 'opacity-100 delay-100 motion-safe:animate-pulse',
false: 'opacity-0',
},
},
},
);
A product card in the platform's screens/ uses NavLink directly. An island organism that renders links to indexable pages, such as ProductRail, takes it as a component prop, linkAs, and renders each card's link with it. NavLink comes from a 'use client' module, so a Server Component may pass it as a prop: React sends it as a client reference, not as a function.
<NavLink href={paths.product(product.id)} className="block">
<ProductCardBody product={product} />
</NavLink>
<ProductRail products={products} linkAs={NavLink} />
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. Write each answer as the section's HTML and JS values in the page's rendering doc (page-rendering.md).
- 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.
- Search engines or the first paint need it → a Server Component that reads caches. Primary content (page-rendering.md) renders in the first flush, from the reads the page entry awaits, even when a read is slow: fix the slow read in the back end. Other content streams 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 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. - It shows the current time or the time left (a countdown, an open-now badge) → the server renders the facts that stay true (the end time, the opening hours), and a small client leaf reads
useClockbehind a same-size skeleton (Time-dependent UI).
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 still renders on the server: in place while it stays within React's 12,800-byte limit (b2c-b2b.md), and after the footer above it; 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', a useQuery while it's pending, or useClock while it's null |
The skeleton the component returns | Auth-dependent parts (step 1), data loaded only in the browser (step 4), and time-dependent parts (step 6) |
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: falsethrows 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>only around a part that loads on its own, never around primary content, and never to move a part to the browser.