The user wants an example of a "partial hydration" pattern using GraphQL, Suspense, and Error Boundaries.
This is a very specific, modern frontend architecture pattern, likely within a React/Next.js context (though the core concepts apply to React generally).
"Partial hydration" (often called "Islands Architecture" or "Component Islands" depending on the framework) usually implies that parts of the server-rendered HTML become interactive on the client, while others remain static.
However, in the context of React and GraphQL, "partial hydration" often refers to:
Server-Side Rendering (SSR) the initial shell.
Streaming HTML (using Suspense) to push down chunks as data resolves.
Hydrating specific parts of the app.
But looking at modern trends (specifically React Server Components - RSC), true partial hydration means only sending JS for interactive parts.
If the user isn't explicitly asking for RSC, I need to balance a standard React SSR approach (Next.js pages router or generic React) with the newer RSC approach (Next.js app router), as "partial hydration" is the defining feature of RSC.
Let's assume the user wants a modern, robust implementation. The best way to demonstrate this today is using Next.js App Router with React Server Components, as this is the standard way to achieve "partial hydration" (only hydrating 'use client' components) combined with GraphQL (via fetch or a client like Apollo/Urql).
However, if they want a pure client-side hydration of specific islands without a full framework like Next.js, that's complex. Given the phrasing "Engineer a... pattern", they likely want a code structure/architecture demonstration.
The Container (Server Component): Fetches data or provides the structure. In RSC, this is a server component.
The Data Layer: How do we get GraphQL data?
Option A (RSC approach): Fetch directly in the Server Component using standard fetch.
Option B (Client approach): The server renders a skeleton, the client hydrates and fetches.
Decision: To show the best modern pattern, I will use a hybrid:
A Server Component that acts as the "Island Container".
It passes initial data (fetched via GraphQL) to a Client Component.
The Client Component handles the interactivity (Hydration) and subsequent client-side fetching.
Suspense: Wrapping the slow parts.
Error Boundary: A class component (or library wrapper) wrapping the fragile parts.
Wait, there's a nuance.
If I fetch in RSC, I don't strictly need client-side hydration unless there's interactivity.
If I want "Partial Hydration", I need:
A Static HTML shell (Server).
A Dynamic Island (Client).
The Island needs data. Does it fetch it, or is it passed in?
Pattern 1: The "Server-First" Hybrid (RSC)
Root (Server): Fetches heavy data via GraphQL (server-side).
Suspense: Waits for data.
Client Component: Receives data as props. Hydrates for interactivity.
Pros: Fast initial load.
Cons: Hydration happens for the whole tree if not careful.
Pattern 2: The "Streamed" Hybrid (RSC)
Root (Server): Renders static shell immediately.
Suspense Boundary: Wraps a component that takes time to fetch.
Inside Suspense (Server): Fetches data, passes to Client Component.
Let's refine the specific request: "Partial hydration pattern mixing client components, suspense boundaries, and error boundaries."
I will construct a Next.js App Router style solution (as it's the de facto standard for this currently) but keep the concepts generic enough to understand the pattern.
Key Elements to Implement:
GraphQL Query: A simple example (e.g., User Profile).
The Error Boundary: A standard React Class Component.
The "Island" (Client Component): An interactive widget (e.g., a "Like" button or a collapsible view) that receives GraphQL data.
The Parent (Server Component): The orchestrator using Suspense.
The Code Structure:
lib/graphql.ts: Helper to fetch.
components/ErrorBoundary.tsx: The safety net.
components/InteractiveProfile.tsx ("use client"): The hydrated island.
app/page.tsx (Server): The layout, suspense, and data fetching integration.
Critique of the "Hybrid Fetching" Pattern:
If I fetch in the Server Component, I block the stream until data is ready (unless using use hook or similar async patterns in RSC).
If I want to demonstrate Suspense, the Server Component must be async.
Let's add a twist: The "Hydrate-on-Interaction" or "Lazy Hydration" concept?
Maybe that's too complex. Let's stick to the standard RSC "Server Component streaming HTML to Client Component" pattern, as that is the industry definition of partial hydration right now (React Server Components).
Wait, what if the user isn't using Next.js 13+?
If they are using standard React (CRA) or older Next.js, "Partial Hydration" usually involves ReactDOM.createPortal or specific libraries like astro mixed with React.
However, the prompt mentions "Suspense boundaries", which strongly points towards React 18+ Concurrent Features.
I will focus on the React 18 + Next.js App Router pattern as it combines all four elements (GraphQL, Client Components, Suspense, Error Boundaries) into a cohesive "Islands" architecture natively.
Detailed Implementation Plan:
Setup: Mock GraphQL fetcher.
Client Component (The Island):
Marked 'use client'.
Interactive (e.g., expand text, click button).
Uses useQuery (client-side) OR receives props. Actually, a true partial hydration pattern often involves the client component taking over the data fetching to ensure interactivity isn't blocked by server latency, OR receiving serialized data.
Better approach: Server Component fetches, passes to Client Component for interactivity. This is the most efficient "partial hydration" (HTML is static, JS hydrates only the button/state logic).
Suspense Boundary:
Wraps the data-fetching node.
Shows a Skeleton.
Error Boundary:
Wraps the Suspense Boundary (or inside, depending on granularity). usually, Error Boundary wraps Suspense to catch the error and replace the loading state with an error state.
Refining the "Mix":
To make it a true "pattern," I should handle the state synchronization.
Scenario:
Server: Fetches "Read-only" data.
Client: Hydrates "Read-write" logic.
Let's create a "UserProfile" widget.
Server Side: Fetches basic user data (Name, Avatar).
Client Side (Island): A "Follow" button and a "Bio" text area that is editable.
Suspense: Shows a shimmer while Server fetches.
Error Boundary: Shows "Failed to load" if GraphQL fails.
Wait, if I fetch in Server, and it fails, the Error Boundary catches it.
If I fetch in Client, the Suspense boundary catches the loading state.
Let's do the "Streamed Hydration" approach.
Container: Server Component.
Suspense: Wraps <UserProfile />.
<UserProfile />: A Server Component that fetches GraphQL.
On Success: Renders <ClientInteractiveProfile data={data} />.
On Fail: Throws error (caught by boundary).
Pending: Suspense catches.
This is the cleanest implementation of the requested stack.
Final Code Layout:
GraphQLClient: Simple wrapper.
ErrorBoundary: Reusable class.
LoadingSkeleton: Visual state.
InteractiveIsland: Client component (the 'hydration' target).
ProfileContainer: Server component (the 'partial' renderer + fetcher).
Let's write the code. I will assume Next.js App Router syntax as it is the standard reference for this architecture.
Self-Correction during drafting:
Make sure to distinguish between Server-Side Rendering (SSR) data fetching and Client-Side data fetching in the explanation.
The "Partial Hydration" pattern implies that the majority of the page is static HTML, and only the <InteractiveIsland /> gets the JavaScript bundle.
I will also include a "Hybrid" approach where the Error Boundary is a Client Component (required because of React event handling) wrapping a Server Component flow.
The Pattern:
GraphQLFetcher: Simulates a latency-prone API.
ErrorBoundary: Standard React pattern.
Suspense: Standard React pattern.
Component Structure:
UserCard (Server Component): Fetches data. Throws promise (suspense) or error.
This creates the architecture: ErrorBoundary -> Suspense -> Server Component (Fetch) -> Client Component (Hydrate).
Let's go.
This pattern implements a "Server-First Partial Hydration" architecture. It is the standard approach in modern frameworks like Next.js (App Router) and Remix, where the server handles data fetching and streaming HTML, while the client only hydrates specific interactive "islands."
The Architecture
GraphQL (Server): Executes the query and streams data.
Suspense (Server/Client): Acts as the streaming boundary. It shows a skeleton immediately and pops in the content when the GraphQL promise resolves.
Error Boundary (Client): Wraps the hydrated component to catch runtime errors or network failures during the stream.
Client Component (Island): The leaf node that receives server data but handles user interactions (state/effects) on the browser.
Implementation
We will use a Next.js App Router structure (React Server Components) as the baseline, as it natively supports this mixing.
1. The GraphQL Fetcher (Server Layer)
First, we need a utility to fetch data. In a real app, this would use a cached client like urql or apollo. Here is a raw fetch wrapper that simulates latency.
typescript
// lib/graphql.ts
const GRAPHQL_ENDPOINT = 'https://graphql.example.com/v1/graphql';
interface GraphQLError {
message: string;
}
export async function query<T>(query: string, variables = {}): Promise<T> {
// Simulate network latency to demonstrate Suspense streaming
await new Promise((resolve) => setTimeout(resolve, 1500));
const res = await fetch(GRAPHQL_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
const json = await res.json();
if (json.errors) {
// Throwing here triggers the Error Boundary on the client
throw new Error(json.errors[0].message);
}
return json.data;
}
2. The Error Boundary (Client Layer)
Since React Server Components cannot be Error Boundaries themselves (they have no state), we need a classic Client Component class to catch rendering errors in the tree below it.
tsx
// components/ErrorBoundary.tsx
'use client'; // This directive ensures this runs on the client
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
public state: State = { hasError: false, error: null };
public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('GraphQL Island Error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="p-4 bg-red-50 border border-red-200 text-red-700 rounded">
<h3 className="font-bold">Something went wrong</h3>
<p className="text-sm">{this.state.error?.message}</p>
</div>
);
}
return this.props.children;
}
}
3. The Interactive Island (Client Layer)
This is the "Hydration" target. It receives data fetched on the server but executes its logic (like toggling, liking, or expanding) in the browser.
tsx
// components/ProfileIsland.tsx
'use client';
import { useState } from 'react';
interface UserProfile {
id: string;
name: string;
email: string;
}
// Props are serialized by the server and passed here
export function ProfileIsland({ user }: { user: UserProfile }) {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div className="p-6 bg-white rounded-lg shadow-sm border">
<div className="flex justify-between items-center">
<h2 className="text-xl font-bold">{user.name}</h2>
<button
onClick={() => setIsExpanded(!isExpanded)}
className="px-3 py-1 text-sm bg-blue-600 text-white rounded"
>
{isExpanded ? 'Collapse' : 'Expand'}
</button>
</div>
{/* Interactive section that hydrates on click */}
{isExpanded && (
<div className="mt-4 pt-4 border-t text-gray-600">
<p>ID: {user.id}</p>
<p>Email: {user.email}</p>
</div>
)}
</div>
);
}
4. The Server Component Orchestrator
This is the glue. It is a Server Component. It fetches the data, wraps the interactive child in Suspense (for loading states) and ErrorBoundary (for failures).
tsx
// app/page.tsx (Server Component)
import { Suspense } from 'react';
import { query } from '@/lib/graphql';
import { ProfileIsland } from '@/components/ProfileIsland';
import { ErrorBoundary } from '@/components/ErrorBoundary';
// 1. Define the query
const GET_USER = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
// 2. Async Server Component
export default function Dashboard() {
return (
<main className="p-8">
<h1 className="text-2xl mb-6">User Dashboard</h1>
{/* 3. Partial Hydration Pattern */}
<div className="grid gap-6">
{/* A. Error Boundary handles GraphQL exceptions */}
<ErrorBoundary>
{/* B. Suspense handles the Streaming/Loading state */}
<Suspense fallback={<ProfileSkeleton />}>
{/* C. The Fetcher Component (Server-Only) */}
<ProfileFetcher id="123" />
</Suspense>
</ErrorBoundary>
</div>
</main>
);
}
// A specialized Server Component to isolate the async fetch
async function ProfileFetcher({ id }: { id: string }) {
// This promise suspends the render until resolved
const data = await query<{ user: any }>(GET_USER, { id });
// Pass server data to Client Component
return <ProfileIsland user={data.user} />;
}
// Skeleton UI (Server Static)
function ProfileSkeleton() {
return (
<div className="animate-pulse p-6 bg-gray-100 rounded-lg">
<div className="h-4 bg-gray-300 rounded w-1/2 mb-4"></div>
<div className="h-4 bg-gray-300 rounded w-3/4"></div>
</div>
);
}
How this flows:
Initial Request: The browser requests /.
Server Render: The server starts rendering Dashboard. It encounters ProfileFetcher.
Suspension: ProfileFetcher initiates the GraphQL request. Because it is async, React pauses rendering this branch.
Streaming: React streams the initial HTML (Shell) to the browser, including the Dashboard layout and the ProfileSkeleton.
Resolution: The GraphQL request finishes (after 1.5s).
Hydration Stream: React streams the real HTML for ProfileIsland down the wire, replacing the skeleton.
Hydration: The browser downloads the JS bundle for ProfileIsland. React "hydrates" the component, attaching the click event listener to the button. No JavaScript was run for the rest of the page.
Failure Mode: If the GraphQL failed, query throws, React catches it near the ErrorBoundary, and renders the fallback UI instead of crashing the whole page.