tsx
// Example: GraphQL Partial Hydration Pattern in Next.js 14+ App Router
// Featuring:
// - Partial Prerendering (PPR) for static shell + dynamic streaming
// - Server Components: Static GraphQL fetches (non-interactive shell)
// - Client Components: Dynamic GraphQL queries with TanStack Query v5 Suspense
// - Suspense Boundaries: Streaming fallbacks (skeletons)
// - Error Boundaries: Isolated error handling for dynamic islands
// - GraphQL: `@graphql-request` for simplicity (server/client), TanStack Query for caching/Suspense
//
// Why this stack?
// - TanStack Query v5: Native `useSuspenseQuery` for React Suspense integration
// - PPR: Static HTML shell streams first, dynamic holes fill via Suspense/streaming
// - Partial hydration: Minimal JS hydration for shell; lazy client bundles for islands
// - Fault-tolerant: Errors isolated, partial failures don't crash page
//
// Run: `npx create-next-app@latest my-app --ts --app` then install deps
// deps: tanstack/react-query@^5.59, graphql-request@^7, graphql@^16, @tanstack/react-query-devtools@^5
1. Setup: next.config.js
Enable Partial Prerendering for static/dynamic streaming.
js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
ppr: 'incremental', // Static shell + dynamic islands (Next.js 14.2+)
},
};
module.exports = nextConfig;
2. GraphQL Schema (Mock Server)
Assume a GraphQL endpoint at /api/graphql (e.g., Apollo Server, Hasura).
graphql
# schema.graphql (for your backend)
type Post {
id: ID!
title: String!
body: String!
author: Author!
tags: [String!]!
}
type Author { name: String! }
type Query {
posts(limit: Int!): [Post!]!
searchPosts(query: String!, tags: [String!]): [Post!]!
}
3. GraphQL Client Utils: lib/graphql.ts
Shared request function.
ts
import { request, gql } from 'graphql-request';
const endpoint = '/api/graphql'; // Your GraphQL server
export const graphqlRequest = (query: string, variables?: any) =>
request(endpoint, query, variables);
4. Providers: app/providers.tsx (Client Component)
Wrap app with TanStack Query. Use devtools for debugging.
tsx
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { useState } from 'react';
export function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient({
defaultOptions: {
queries: {
suspense: true, // Enable Suspense by default
staleTime: 5 * 60 * 1000, // 5min cache
retry: 1,
},
},
}));
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}
5. Root Layout: app/layout.tsx (Server Component)
Static shell, providers.
tsx
import { Providers } from './providers';
import './globals.css';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
6. Error Boundary: components/ErrorBoundary.tsx (Client)
Catches errors in dynamic islands (e.g., GraphQL failures).
tsx
'use client';
import { Component, ErrorInfo, ReactNode } from 'react';
interface Props { children: ReactNode; fallback?: ReactNode; }
interface State { hasError: boolean; error?: Error; }
export class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Dynamic island error:', error, errorInfo);
// Optional: Sentry/log
}
resetError = () => this.setState({ hasError: false });
render() {
if (this.state.hasError) {
return (
<div className="p-4 border rounded-lg bg-red-50 text-red-800">
<h3>Something went wrong in this section.</h3>
<pre>{this.state.error?.message}</pre>
<button onClick={this.resetError} className="mt-2 px-4 py-1 bg-red-600 text-white rounded">
Retry
</button>
</div>
);
}
return this.props.children;
}
}
7. Suspense Fallback (Skeleton): components/Skeleton.tsx
tsx
export function PostSkeleton() {
return (
<div className="animate-pulse p-4 border rounded-lg bg-gray-50">
<div className="h-6 bg-gray-200 rounded mb-2" />
<div className="h-4 bg-gray-200 rounded w-3/4 mb-1" />
<div className="h-3 bg-gray-200 rounded w-1/2" />
</div>
);
}
export function SearchSkeleton() {
return <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-6">{Array(6).fill(<PostSkeleton />)}</div>;
}
8. Dynamic Client Island: components/SearchPosts.tsx (Client)
Uses useSuspenseQuery for GraphQL. Suspends until data loads.
tsx
'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import { graphqlRequest, gql } from '@/lib/graphql';
import { PostSkeleton } from './Skeleton';
const SEARCH_POSTS = gql`
query SearchPosts($query: String!, $tags: [String!]) {
searchPosts(query: $query, tags: $tags) {
id
title
body
author { name }
tags
}
}
`;
interface SearchPostsProps {
initialQuery: string;
tags: string[];
}
export function SearchPosts({ initialQuery, tags }: SearchPostsProps) {
const { data } = useSuspenseQuery({
queryKey: ['searchPosts', initialQuery, tags],
queryFn: () => graphqlRequest(SEARCH_POSTS, { query: initialQuery, tags }),
});
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{data.searchPosts.map((post: any) => (
<div key={post.id} className="p-4 border rounded-lg hover:shadow-md">
<h3 className="font-bold text-lg mb-2">{post.title}</h3>
<p className="text-gray-600 mb-2">{post.body.slice(0, 100)}...</p>
<p>By {post.author.name}</p>
<div className="flex flex-wrap gap-1 mt-2">
{post.tags.map((tag: string) => (
<span key={tag} className="text-xs bg-blue-100 px-2 py-1 rounded">
{tag}
</span>
))}
</div>
</div>
))}
</div>
);
}
9. Page: app/page.tsx (Server Component)
Core Pattern Here:
- Static GraphQL fetch (shell).
- Dynamic island: Suspense + ErrorBoundary around client component.
- PPR streams static HTML first, then hydrates/fills islands incrementally.
tsx
import { graphqlRequest, gql } from '@/lib/graphql';
import { Suspense } from 'react';
import { SearchSkeleton } from '@/components/Skeleton';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { SearchPosts } from '@/components/SearchPosts';
// Static server fetch (PPR static by default)
async function getStaticPosts() {
const STATIC_POSTS = gql`
query StaticPosts {
posts(limit: 3) {
id
title
author { name }
}
}
`;
return graphqlRequest(STATIC_POSTS);
}
export default async function Page() {
const staticData = await getStaticPosts();
return (
<main className="container mx-auto p-8">
{/* Static Shell: Server-rendered, no hydration needed */}
<header className="text-center mb-12">
<h1 className="text-4xl font-bold mb-4">GraphQL Partial Hydration Demo</h1>
<p className="text-xl text-gray-600">
Static posts load instantly. Dynamic search streams in Suspense.
</p>
</header>
{/* Static Posts List */}
<section className="mb-12">
<h2 className="text-2xl font-semibold mb-4">Featured Posts (Static)</h2>
<ul className="space-y-4">
{staticData.posts.map((post: any) => (
<li key={post.id} className="p-6 border rounded-lg bg-green-50">
<h3 className="font-bold">{post.title}</h3>
<p>By {post.author.name}</p>
</li>
))}
</ul>
</section>
{/* Dynamic Island: Partial Hydration + Streaming */}
<section>
<h2 className="text-2xl font-semibold mb-6">Live Search (Dynamic)</h2>
<p className="mb-4 text-gray-600">
This island hydrates client-side only. Errors isolated.
</p>
<ErrorBoundary fallback={<div>Search failed. Reload page?</div>}>
<Suspense fallback={<SearchSkeleton />}>
{/* Client component auto-hydrates here */}
<SearchPosts initialQuery="React Suspense" tags={['graphql', 'nextjs']} />
</Suspense>
</ErrorBoundary>
</section>
</main>
);
}
How It Works (Partial Hydration Flow)
- Server Render (PPR): Static shell (header, featured posts) renders to HTML instantly via server GraphQL. No JS needed.
- Streaming: Browser gets static HTML.
<Suspense> boundaries stream dynamic HTML + JS bundles lazily.
- Client Hydration:
- Minimal shell hydration.
SearchPosts client component hydrates only when scrolled into view (code-split).
useSuspenseQuery suspends → shows <SearchSkeleton /> → fetches GraphQL → renders.
- Error Isolation: GraphQL error (e.g., network fail)? ErrorBoundary catches only the island. Rest of page intact.
- Caching/Hydration: TanStack Query caches data client-side. Re-renders fast. Prefetches via
queryKey.
- Dev/Prod: PPR optimizes bundles. Suspense enables code-splitting per island.
Enhancements
- Prefetching: Add
prefetchQuery in useEffect for optimistic UI.
- Mutations: Use
useMutation inside islands (Suspense-compatible).
- Relay/Apollo: Swap TanStack Query for Relay (
useFragment, useLazyLoadQuery) for compiler-optimized GraphQL.
- PPR Dynamic: Mark islands
export const dynamic = 'force-dynamic'; if server data needed.
- Testing: Mock
graphqlRequest, test boundaries with act() + thrown errors.
This pattern scales to dashboards, e-commerce (static catalogs + dynamic carts). Production-ready! 🚀