Master the React 19 dual-component model, serializable flight boundaries, component-level micro-caching with <DinouCacheSlot>, Partial Prerendering (PPR), and high-performance rendering strategies in Dinou.
Dinou is built natively on the React 19 Server Components (RSC) specification. Rather than treating your entire application as a single monolithic client-side bundle, Dinou partitions components into two distinct execution environments:
"use client".useState), event listeners (onClick), and browser APIs.Think of Server Components as the backbone of your application that orchestrates data fetching, layouts, and non-interactive UI (rendering pure HTML with zero client JavaScript). Client Components act as interactive "islands" or leaves embedded inside the server tree.
On initial page load, Dinou multiplexes the rendered HTML and the segmented React Flight RSC payloads inline in a single server pass (with zero extra hydration fetches and zero hydration mismatches). The browser consumes this stream without ever downloading the JavaScript source code of your Server Components.
In Dinou, every component is a Server Component by default unless explicitly marked with "use client". They execute exclusively on the server and never ship their implementation code to the browser.
async functions. You can await database queries, microservices, or files directly inside the component body.getContext()): Read incoming req.cookies, req.headers, req.query, response helpers (res), unified server/Edge bindings (env), and plugin/middleware data directly on the server via getContext() from "dinou", "./dinou", or "dinou/server".<Suspense>, the layout shell and fallback UI can be delivered immediately without waiting for slow queries, while data streams progressively into the HTTP response.// src/users/page.tsx (Server Component by default)
import { db } from "@/lib/db"; // Never bundled to the client!
export default async function UsersPage() {
// Direct backend query without an intermediary REST API
const users = await db.user.findMany({ take: 10 });
return (
<main className="p-8 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold">Registered Users</h1>
<ul className="mt-4 divide-y">
{users.map((user) => (
<li key={user.id} className="py-2 flex justify-between">
<span>{user.name}</span>
<span className="text-xs font-mono text-muted-foreground">{user.email}</span>
</li>
))}
</ul>
</main>
);
}Static by Default (SSG): In Dinou, this page is pre-rendered at build time by default. The database query runs during npm run build, serving static HTML to visitors with instant TTFB (0ms server wait).
Dynamic Routes: If the route is marked dynamic (e.g. revalidate = 0 in page_functions.ts or reading cookies), a top-level await blocks the entire HTTP response until the query finishes. To preserve instant TTFB on dynamic routes, delegate the await to a child component wrapped in React <Suspense>.
By delegating asynchronous queries to child components wrapped in <Suspense>, the outer layout and fallback UI are sent immediately:
// src/users/page.tsx - Non-blocking streaming layout
import { Suspense } from "react";
import { db } from "@/lib/db";
import { UsersSkeleton } from "./skeleton";
export default function UsersPage() {
return (
<main className="p-8 max-w-4xl mx-auto">
{/* 1. The outer shell is sent immediately (instant TTFB) */}
<h1 className="text-2xl font-bold">Registered Users</h1>
{/* 2. Displays fallback while the child query resolves */}
<Suspense fallback={<UsersSkeleton />}>
<UsersList />
</Suspense>
</main>
);
}
// Child component handles the async query independently
async function UsersList() {
const users = await db.user.findMany({ take: 10 });
return (
<ul className="mt-4 divide-y">
{users.map((u) => (
<li key={u.id} className="py-2 flex justify-between">
<span>{u.name}</span>
<span className="text-xs font-mono text-muted-foreground">{u.email}</span>
</li>
))}
</ul>
);
}The behavior of <Suspense> and fallback skeletons changes fundamentally depending on whether your route is static, dynamic, or hybrid:
Build-Time Resolution: During npm run build, the compiler awaits the <Suspense> promise to resolve completely and writes the final resolved HTML directly into the static file.
Fallback Behavior: Visitors never see the loading skeleton because the fallback is eliminated once the build finishes.
Trade-off: 0ms TTFB from CDN edge, but data reflects build-time state (stale until next build/revalidation).
On-Demand Streaming: On every HTTP request, the server executes the route and immediately streams the shell and <Suspense fallback={<Skeleton />}> skeleton over the open HTTP connection.
Fallback Behavior: The user sees the skeleton while waiting, and React streams the resolved HTML chunk when the query finishes.
Trade-off: 100% fresh data and non-blocking layout, but incurs continuous server compute costs, DB load, and request-time latency.
Static Shell Prerender: When ppr = true is enabled on the segment (or globally in dinou.config.ts), the outer layout shell and fallback skeleton are pre-rendered at build time and served immediately with 0ms TTFB from the CDN edge.
Fallback & Static Opt-Out: The skeleton renders instantly from static cache while live data streams into the hole—or call noDynamic() synchronously at the top of an async component to resolve that specific <Suspense> boundary at build time inside shell.html.
Trade-off: Combines the instant delivery of SSG with the fresh, live data of dynamic SSR at minimal server compute cost.
Because Server Components do not execute in the browser, they cannot use browser-specific or client-interactive features:
useState, useEffect, useReducer).onClick, onChange, onSubmit).window, document, localStorage, navigator).createContext, useContext, or use(Context)). To share React Context with client subtrees, define the context and provider inside a "use client" wrapper component and render that wrapper from your Server Component, passing Server Components through children.1. React 19 Stateless Synchronous Hooks: Inside synchronous Server Components (never inside async Server Components), you can freely use useId(), use(promise), useMemo(), useCallback(), and useDebugValue(). Dinou scopes server-generated useId() values deterministically across layouts, pages, <DinouCacheSlot> boundaries, and PPR dynamic holes with zero hydration mismatches.
2. Dinou Universal Navigation Hooks: usePathname() and useSearchParams() (imported from "dinou" or "./dinou") work seamlessly in both Server Components (synchronous or async) and Client Components. Note that calling useSearchParams() inside a Server Component reads the live request query string and opts the route into Dynamic SSR, whereas calling it inside a Client Component reads window.location.search in the browser and preserves static SSG, ISR, PPR, and export-static.
Client Components provide rich, real-time client-side interactivity. They enable event handlers, local component state, animations, and access to browser APIs.
Client Components have complete access to the client-side React ecosystem:
useState, useReducer, and React 19 useActionState.useEffect and useLayoutEffect.localStorage, Geolocation, IntersectionObserver, Audio).A common point of confusion is assuming Client Components execute exclusively in the browser. Client Components are pre-rendered on the server to HTML during initial page load to ensure fast First Contentful Paint (FCP) and SEO indexing.
const token = localStorage.getItem("token")) will throw a server runtime error. Read browser-only state inside useEffect or event handlers—avoid branching JSX output on typeof window !== "undefined" during render, as rendering different initial HTML on the server and client causes a React hydration mismatch (reserve typeof window !== "undefined" guards for imperative logic that does not alter initial markup).To declare a component as a Client Component, add the "use client" directive at the very top of the file, before any import statements or executable code (leading comments are allowed).
The directive is not a runtime function call—it is an instruction to the bundler (esbuild, Rollup, Webpack) that defines the network split point:
"use client"; // Must appear before any imports or code!
import { useState } from "react";
export function Counter({ initial = 0 }: { initial?: number }) {
const [count, setCount] = useState(initial);
return (
<button
onClick={() => setCount((c) => c + 1)}
className="px-4 py-2 bg-blue-600 text-white rounded-lg font-medium"
>
Count: {count}
</button>
);
}Once a file declares "use client", all components, utility modules, and third-party libraries imported by that file are automatically treated as part of the client bundle. You do not need to add "use client" to child modules imported by a Client Component.
Exception — Server Functions ("use server"): Modules or exported functions marked with "use server" can be imported directly into Client Components. Dinou compiles them into lightweight RPC stubs for the browser while keeping their implementation strictly on the server.
When passing props from a Server Component to a Client Component, data crosses the network boundary (serialized as React Flight JSON). Props passed across this boundary must be serializable.
string, number, bigint, boolean, null, undefined, and global Symbol.for(...).{ id: 1, name: "Dinou" }).Date, Map, Set, and TypedArrays (e.g. Uint8Array) are serialized and reconstructed by React 19 Flight.children or named slots.await from Server to Client (unwrapped with React 19 use())."use server".onClick={() => ...}) from Server Components.Symbol() instances and memory-bound weak collections.window, document.body).React 19 and Dinou support passing an unresolved Promise (or an array of Promises) as a prop from a Server Component to a Client Component without awaiting it on the server. Inside a <Suspense> boundary, the Client Component reads each promise with the use() hook, streaming the resolved data without blocking TTFB:
import { Suspense } from "react";
import { UserProfile } from "./user-profile"; // "use client"
export default function Page() {
// Start fetching without awaiting!
const userPromise = fetchUserData();
return (
<Suspense fallback={<div>Loading profile skeleton...</div>}>
<UserProfile userPromise={userPromise} />
</Suspense>
);
}"use client";
import { use } from "react";
export function UserProfile({ userPromise }: { userPromise: Promise<{ name: string }> }) {
// Unwraps the promise value seamlessly
const user = use(userPromise);
return <h2>Hello, {user.name}</h2>;
}Behavior with Partial Prerendering (ppr = true): Wrapping a Client Component that receives an un-awaited Promise prop (or array of Promises) inside <Suspense> automatically registers that boundary as a Dynamic PPR Hole—the outer shell and <Suspense> fallback are pre-rendered at build time for 0ms TTFB, while the promise streams live at request time.
Dinou empowers you to choose the exact architectural balance between server performance and client ergonomics. Follow these battle-tested patterns for optimal architecture:
Keep your layouts, route pages, and static wrappers as Server Components. Only push the "use client" boundary down to the small, interactive "leaf" components (such as an upvote button, search box, or dropdown menu).
Folder naming note: Any subfolder without a page.tsx or layout.tsx (such as src/dashboard/components/) is automatically ignored as a URL route. Do not prefix active component folders with _ (_components/), as _* directories are excluded from Dinou's router and client manifests for parking inactive code.
A Client Component cannot directly import a Server Component (because bundling a Server Component into the client module would defeat the RSC boundary). However, a Client Component can receive Server Components as children or via named props!
import { ModalContainer } from "./ModalContainer";
import { HeavyServerProfile } from "./HeavyServerProfile"; // Server Component
export default function Page() {
return (
<ModalContainer>
{/* HeavyServerProfile remains 100% on the server! */}
<HeavyServerProfile />
</ModalContainer>
);
}"use client";
import { useState, type ReactNode } from "react";
export function ModalContainer({ children }: { children: ReactNode }) {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
{isOpen && (
<div className="modal-backdrop">
{/* children is rendered on the server and passed as pre-rendered JSX! */}
{children}
</div>
)}
</div>
);
}If you are building an interactive canvas, video editor, or complex SPA dashboard and prefer traditional React where you can use useState and onClick anywhere in the page without boundary splitting, use Dinou's Client-First Model:
"use client";
import { useState } from "react";
import type { PageProps } from "./dinou";
import type { ProjectData } from "./page_functions";
export default function CanvasPage({
project,
}: PageProps<ProjectData>) {
// Full access to state, effects, and events everywhere in the file!
const [layers, setLayers] = useState(project.initialLayers);
return (
<div onClick={() => console.log("clicked")}>
<Toolbar onAddLayer={(l) => setLayers([...layers, l])} />
<Stage layers={layers} />
</div>
);
}import type { PageFunctions } from "./dinou";
import { db } from "@/lib/db";
export interface ProjectData {
project: { id: string; initialLayers: string[] };
}
// Runs securely on the server (params is pre-typed as { id: string } | undefined)
export const getProps: PageFunctions<ProjectData>["getProps"] = async (
params
) => {
const project = await db.projects.findById(params?.id ?? "");
return { project };
};Advantage: Fast development speed and traditional React ergonomics, with secure backend data fetching and SSR pre-rendering intact.
Non-Blocking Streaming Tip: getProps can also return un-awaited Promises (e.g. { project, commentsPromise }) so your Client-First page flushes its interactive shell immediately and unwraps slow queries inside <Suspense> via React 19's use() hook without blocking TTFB.
A common architectural trap in dynamic RSC applications is converting heavy server widgets into Client Components just to gain client-side memory caching (such as SWR or TanStack Query). In Dinou, <DinouCacheSlot> provides component-level server caching (Vertical Segmentation) directly in the RSC layer.
To avoid running an expensive 2-second database query on every dynamic page load, developers often convert the widget to "use client" with a client cache. This bloats the client JS bundle, loses direct database access, exposes internal API endpoints, and introduces client-side network waterfalls.
Keep the component on the server! <DinouCacheSlot> caches the rendered RSC Flight payload of that specific subtree on the server for a designated TTL (e.g. revalidate={300}). The rest of the page remains 100% dynamic, while the expensive subtree serves in ~0–2ms.
Yes, absolutely. While <DinouCacheSlot> itself is an async Server Component that executes exclusively on the server, its children can freely render interactive Client Components (and pass "use server" functions as props). Dinou caches the Client Component reference along with its pre-computed server props, and the browser hydrates it normally with full interactivity:
import { Suspense } from "react";
import { DinouCacheSlot } from "dinou/server";
import { db } from "@/lib/db";
import { UserGreeting } from "./UserGreeting"; // Reads user session/cookies
import { GreetingSkeleton, AnalyticsSkeleton } from "./skeletons";
import { InteractiveChart } from "./interactive-chart"; // Client Component
// Server Component performing the heavy query
async function HeavyAnalyticsWidget() {
const analyticsData = await db.analytics.aggregateBigData(); // 2-second query
return <InteractiveChart data={analyticsData} />;
}
export default function DashboardPage() {
return (
<main className="space-y-6 p-8">
{/* Dynamic personal component: reads cookies/session without blocking initial layout delivery (preserves fast TTFB) */}
<Suspense fallback={<GreetingSkeleton />}>
<UserGreeting />
</Suspense>
{/* Micro-ISR slot: wrapped in Suspense so a cold cache miss streams without blocking TTFB */}
<Suspense fallback={<AnalyticsSkeleton />}>
<DinouCacheSlot id="analytics-slot" revalidate={300} tags={["analytics"]}>
<HeavyAnalyticsWidget />
</DinouCacheSlot>
</Suspense>
</main>
);
}"use client";
import { useState } from "react";
export function InteractiveChart({ data }: { data: any }) {
const [zoom, setZoom] = useState(1);
return (
<div className="p-4 border rounded-lg bg-card">
<div className="flex justify-between items-center mb-2">
<span className="text-sm font-bold">Metrics (Zoom: {zoom}x)</span>
<button
onClick={() => setZoom((z) => z + 1)}
className="px-2 py-1 text-xs bg-primary text-primary-foreground rounded"
>
Zoom In
</button>
</div>
<canvas data-zoom={zoom} />
</div>
);
}Why wrap in <Suspense>? On a Dynamic SSR route there is no pre-rendered static HTML—the server renders the response on every request. Wrapping <DinouCacheSlot> in <Suspense> ensures that on a cold cache miss (when the slot is not cached yet), the server streams the page layout and <AnalyticsSkeleton /> immediately instead of blocking TTFB for the 2-second query. On cache hits (and across expired TTLs via Background SWR), <DinouCacheSlot> resolves from the server slot cache (~1–2ms) without suspending, so the SSR response includes the rendered widget directly without showing the skeleton fallback.
What about UserGreeting? Wrapping UserGreeting in <Suspense> ensures that fetching user session data does not delay flushing the outer page layout during SSR (and on PPR routes, keeps session/cookie access isolated inside a dynamic hole).
In-Place Client Refresh & State Preservation: Any Client Component can trigger an on-demand re-render of this slot by id, by cache tag, or across all mounted slots ("*") using await refreshSlot("analytics-slot") from "dinou" (or pass { fresh: true } to bypass the server slot cache as well). React reconciles the new server props in place without unmounting <InteractiveChart />, preserving its local zoom state!
On-Demand Server Invalidation: Server Functions and webhooks can purge and update the slot cache globally via await revalidateTag("analytics") from "dinou/server".
<DinouCacheSlot> across Dynamic SSR, Static/ISR, and Partial Prerendering (including <Suspense> nesting-order semantics, nested slots, and when not to use a slot), see Vertical Axis: Micro-ISR (<DinouCacheSlot>) and Pairwise Synergy #3: Vertical + Temporal (PPR).While child pages passed via {children} remain Server Components, marking src/layout.tsx with "use client" forces every module imported by the root layout into the global client JS bundle across all routes, and prevents src/layout.tsx itself from being async, querying databases/secrets directly, or rendering <DinouCacheSlot> directly. Keep src/layout.tsx as a Server Component and extract interactive UI (such as a <Navbar /> or <ThemeProvider>) into dedicated Client Components instead.
Never write import ServerComponent from "./ServerComponent" inside a file containing "use client". Use the Composition Pattern (Section 6.2) and pass it as children instead.
Calling window.innerWidth or localStorage.getItem() outside of a useEffect in a Client Component causes server pre-rendering crashes. Always wrap browser calls in useEffect or an event handler.
Do not pass callback functions or ORM model class instances with methods as props to Client Components. Extract plain JavaScript objects or use Server Functions ("use server") for actions.