We are going to design a pattern for partial hydration in a GraphQL context, mixing client components, suspense boundaries, and error boundaries.
The idea is to have a page that fetches some data on the server (for initial load) and then hydrates parts of the page on the client as needed.
We'll use:
- Server Components (RSC) for the initial server-rendered page.
- Client Components for interactive parts that require client-side state or effects.
- Suspense boundaries for handling loading states for asynchronous operations (like client-side data fetching).
- Error boundaries for handling errors in client components.
Steps:
- We assume we are using a framework that supports React Server Components (like Next.js 13+ with app directory).
- We'll have a page (server component) that fetches some initial data via GraphQL (using a server-side GraphQL client).
- The page will pass some of that data to client components as props.
- The client components might have their own data fetching (for example, for data that is not needed for the initial render or that updates frequently).
- We'll wrap the client components in Suspense boundaries to show a fallback while they are loading.
- We'll also wrap the client components in error boundaries to catch and display errors.
However, note that in React, error boundaries are class components (or use the useErrorBoundary hook in some frameworks) and cannot be used inside client components that are function components? Actually, we can use a class component as an error boundary and then wrap our client component.
But note: In React 18, we can use the use hook and Suspense for data fetching, and error boundaries for catching errors. However, error boundaries only catch errors in the render phase, lifecycle methods, and constructors of their child components.
We are going to structure:
Page (Server Component)
|
|-- Some static content (server-rendered)
|
|-- ClientComponent1 (wrapped in Suspense and ErrorBoundary)
| This component might fetch its own data on the client (using a GraphQL query that is not needed for the initial page)
|
|-- ClientComponent2 (wrapped in Suspense and ErrorBoundary)
| Similar to above, maybe a different query.
However, note that the server component can already fetch data and pass it to the client components. So why would we fetch again on the client?
We might have two scenarios:
a) The data for the client component is not needed for the initial render (so we don't fetch it on the server for that component) and we want to load it asynchronously on the client.
b) The data for the client component is updated frequently and we want to refetch on the client.
But in our pattern, we are mixing: the server component can fetch some data and pass it to the client component, and the client component can also have its own client-side fetching.
However, if the server component already fetched the data, we can pass it as a prop and avoid client-side fetching for that piece of data. But if we want to update it on the client, we might still do a client-side fetch.
But note: the goal is partial hydration. We want to hydrate only the parts that need to be interactive, and for the data that is static, we can keep it server-rendered.
Let's assume:
We have a page that shows a list of posts. The server component fetches the list of posts (for the initial 10) and passes them to a client component that handles pagination and infinite scroll.
The client component will then fetch more posts on the client when the user scrolls.
So:
Page (Server Component) -> fetches initial 10 posts via GraphQL on the server.
Then renders:
But the ClientPostList will also have its own client-side data fetching for the next pages.
However, we also want to handle errors and loading states for the client-side fetching.
So in the ClientPostList, we might have:
const [posts, setPosts] = useState(initialPosts);
const [page, setPage] = useState(1);
const loadMore = async () => {
const newPosts = await fetchMorePosts(page);
setPosts(prev => [...prev, ...newPosts]);
}
But then we are using a client-side fetch. We can use Suspense for the initial client-side fetch? Actually, the initial data is already there.
Alternatively, we can design the client component to use a GraphQL query that is executed on the client (using a client-side GraphQL client like Apollo or Relay) and then use Suspense for that query.
However, if we are using a client-side GraphQL client, we might not want to pass the initial data from the server because the client-side cache might have a different structure.
But in the context of partial hydration, we want to avoid rendering a loading state for the initial data because we already have it from the server.
So we can do:
Option 1: Use the same GraphQL query on the client and use the defer or @defer directive to split the query? But that's a GraphQL feature and might not be supported by all clients.
Option 2: Use a hybrid approach: the server component fetches the initial data and passes it as a prop to the client component, and then the client component uses a client-side GraphQL client to fetch more data and updates its own state.
But then we are not using Suspense for the initial data because we already have it. We can use Suspense for the subsequent fetches.
Alternatively, we can use Suspense for the entire client component and then have the server component pass the initial data as a prop that the client component uses to initialize its cache? This is getting complex.
Let's simplify:
We are going to have:
Page (Server Component) -> fetches initial data for a part of the page (say, a widget) and passes it to a ClientWidget.
The ClientWidget is a client component that might also have its own data fetching (for real-time updates, for example). But for the initial render, it uses the passed data.
We want to avoid a flash of loading state for the initial data because we already have it.
So we wrap the ClientWidget in a Suspense boundary that only shows a fallback for the client-side data fetching that happens after the initial render? But Suspense doesn't distinguish between initial and subsequent data.
Alternatively, we can design the client component to not use Suspense for the initial data, but only for the updates.
However, React Suspense for data fetching is designed to work for the initial render as well.
Another idea: use two Suspense boundaries? One for the initial data (which we already have, so we don't need to show a fallback) and one for the updates? But that's not straightforward.
Let's think about the pattern we want:
We want the server to render the initial state of the component, and then on the client, the component hydrates with that initial state and then might fetch additional data.
In React 18, we can use use hook in server components to fetch data, but in client components we can use use in combination with a resource that is already available? Not exactly.
Alternatively, we can use a pattern where the client component uses a client-side data fetching library that supports rehydration of the initial server state (like Apollo's ssr and hydrate).
But the question is about a pattern that mixes client components, suspense, and error boundaries without specifying the data fetching library.
Let's design a pattern that is library-agnostic:
We'll have:
1. A server component that fetches data via GraphQL (using any server-side GraphQL client) and passes the data as a prop to a client component.
2. The client component receives the initial data as a prop and sets its state to that.
3. The client component also has a function to fetch more data (or refresh) which uses a client-side GraphQL client (or fetch) and updates its state.
4. We wrap the client component in a Suspense boundary for the client-side data fetching? But the initial render doesn't need to suspend because we have the prop.
5. We can use a separate component for the client-side data fetching that uses `use` (if we are using React 18+ and the data fetching returns a promise) and then we wrap that in Suspense.
However, the client component might be doing multiple things. We want to separate the initial data (from server) and the client-side updates.
Alternatively, we can have:
<Suspense fallback={<div>Loading more...</div>}>
<ClientComponent initialData={initialData} />
</Suspense>
And in the ClientComponent, we do:
const [data, setData] = useState(initialData);
// Then, when we need to fetch more, we do:
const moreData = await fetchMore(); // This returns a promise, and we can use `use` if we are in a component that supports it? But `use` is for server components and for client components in React 18? Actually, `use` is a React function that can be used in Client Components in React 18.
But note: `use` is a hook that works only in Client Components and Server Components? Actually, `use` is a React primitive that works in both, but it is intended for use with resources (promises) that are fetched in Server Components and then passed to Client Components? Or we can create a resource in a Client Component?
According to React documentation, we can use `use` in Client Components to read a resource (a promise) that was created in a Server Component and passed down, or that was created in a Client Component? Actually, we can create a resource in a Client Component with `use`? No, `use` is for reading a resource, not creating.
So we might create a resource (a promise) in the ClientComponent and then use `use` to read it? But then we are back to the same problem: we don't want the initial read to suspend because we have the prop.
Alternatively, we can avoid using `use` for the initial data and only use it for subsequent fetches? But then we have two sources of truth.
Given the complexity, let's consider a different approach:
We can have the client component accept a prop `initialData` and then use a client-side data fetching library that supports rehydration. For example, with Apollo:
const client = useApolloClient();
// Use the initialData to write to the cache? Then the component can use a GraphQL query that will read from the cache and then fetch if needed.
But then we are not using Suspense for the initial data because the cache is already populated.
However, if we are using React's built-in Suspense for data fetching, we might not have a cache.
Given the constraints, I think we need to accept that:
- The initial data is passed as a prop and does not cause a Suspense fallback.
- Any additional data fetching on the client that returns a promise can be wrapped in a Suspense boundary.
But how do we trigger a Suspense boundary only for the client-side fetch and not for the initial render?
We can split the client component into two:
<ClientComponent initialData={initialData} />
Inside ClientComponent:
const [data, setData] = useState(initialData);
// For subsequent fetches, we can do:
const [resource, setResource] = useState(null);
const loadMore = async () => {
const newResource = fetchMoreData(); // returns a promise
setResource(newResource);
}
// Then, we can have a child component that uses `use(resource)` when resource is set.
But then we need to conditionally render the child that uses `use` only when we are fetching more? And wrap that child in Suspense?
Alternatively, we can have:
let additionalData;
if (resource) {
additionalData = use(resource); // This will suspend until the promise resolves.
}
Then, we combine the initialData and additionalData.
But note: the initial render of the client component does not have `resource` set, so it doesn't suspend. Only when we set the resource (when we trigger a fetch) then the component that uses `use(resource)` will suspend.
However, the entire client component will suspend if we call `use` conditionally? Actually, if we call `use` conditionally, it might break the rules of hooks. We cannot conditionally call `use`.
So we have to call `use` unconditionally. We can do:
const resource = useSomeResource(); // This resource is a promise that might be already resolved or not.
But then how do we avoid suspending on the initial render? We can have the resource be a promise that is already resolved for the initial data? But then we are mixing the initial data and the additional data.
Given the complexity, I think we need to step back and consider:
The pattern we are trying to achieve is:
- Server renders the initial state (with some data).
- Client hydrates and then may fetch more data without showing a loading state for the initial data.
This is similar to how Next.js 13's `use` hook works in server components, but for client components we don't have a direct equivalent.
After research, I found that in React 18, we can use `use` in client components for a resource that is passed from a server component. But if we create the resource in the client component, we cannot use `use` for that resource? Actually, we can create a resource in a client component by using a promise that is stored in a ref and then use `use` on that promise? But `use` expects a resource that is a thenable (promise) and will suspend until it resolves.
However, if we create the promise in the client component and then immediately use `use` on it, it will suspend immediately because the promise is not yet resolved. So we don't want that for the initial data.
So maybe we don't use `use` for the initial data, and only use it for the additional fetches? But then we have two different data sources.
Given the time, I propose a pattern that uses:
- The server component fetches the initial data and passes it as a prop.
- The client component uses that prop to set its state.
- The client component, when it needs to fetch more, creates a new promise and sets it to a state variable, and then uses `use` on that state variable? But we cannot conditionally call `use`.
Alternatively, we can have:
const [additionalResource, setAdditionalResource] = useState(null);
// Then, when we want to fetch more:
const loadMore = async () => {
const newResource = fetchMoreData(); // returns a promise
setAdditionalResource(newResource);
}
// Then in the render:
let additionalData;
if (additionalResource) {
additionalData = use(additionalResource);
}
But this is conditionally calling `use`, which is not allowed.
So we must call `use` unconditionally. We can do:
const additionalData = additionalResource ? use(additionalResource) : null;
But again, conditionally calling `use` is not allowed.
The only way to conditionally suspend is to conditionally render a component that uses `use`. So we can do:
{additionalResource && <AdditionalDataComponent resource={additionalResource} />}
And in AdditionalDataComponent:
const data = use(resource);
Then, when additionalResource is set, the AdditionalDataComponent will be rendered and will suspend until the resource resolves.
This way, the initial render of the client component does not suspend because it doesn't render the AdditionalDataComponent until additionalResource is set.
So the pattern:
Page (Server Component)
|
|-- passes initialData to ClientComponent
ClientComponent:
- state: initialData (from prop) and additionalResource (null initially)
- when we need to fetch more, we set additionalResource to a promise (from fetchMoreData)
- we render:
<div>
{initialData.map(...)}
{additionalResource && <AdditionalDataComponent resource={additionalResource} />}
</div>
And we wrap the ClientComponent in a Suspense boundary that will show a fallback when the AdditionalDataComponent is suspended.
But note: the Suspense boundary will also catch errors from the AdditionalDataComponent? We can wrap the AdditionalDataComponent in an error boundary? Actually, we can wrap the ClientComponent in an error boundary to catch errors in the entire client component, including the AdditionalDataComponent.
However, the AdditionalDataComponent is a separate component, so we can wrap it in its own error boundary? But we want the error boundary to catch errors from the client component as a whole.
Let's structure:
Page (Server Component)
|
|-- <ErrorBoundary fallback={<Error />}>
<Suspense fallback={<LoadingMore />}>
<ClientComponent initialData={initialData} />
</Suspense>
</ErrorBoundary>
ClientComponent:
const [additionalResource, setAdditionalResource] = useState(null);
const loadMore = async () => {
setAdditionalResource(fetchMoreData());
}
return (
<div>
{initialData.map(...)}
{additionalResource && <AdditionalDataComponent resource={additionalResource} />}
<button onClick={loadMore}>Load More</button>
</div>
)
AdditionalDataComponent:
const data = use(resource);
return <div>{data.map(...)}</div>
This way:
- The initial data is rendered immediately (no suspense for initial data).
- When we click "Load More", we set additionalResource to a promise, which causes AdditionalDataComponent to render and suspend until the promise resolves.
- The Suspense boundary around ClientComponent will show the <LoadingMore /> fallback while the additional data is loading.
- The ErrorBoundary will catch any errors in ClientComponent (including in AdditionalDataComponent) and show the <Error /> fallback.
But note: the initial data might also cause an error in the ClientComponent? For example, if we try to render initialData and there's an error in the rendering logic. The ErrorBoundary will catch that too.
However, the initial data is passed from the server and we assume it's valid? But it could be invalid or the rendering code could have a bug.
This pattern works for the client-side additional data fetching.
But what if the client component itself does some other asynchronous operation that we want to show a loading state for? We can use the same pattern: have a resource state and conditionally render a component that uses `use` on that resource.
However, if we have multiple asynchronous operations, we might need multiple resources and multiple conditional components.
Alternatively, we can have a single resource that is an object with multiple promises? But then we would have to wait for all of them? Not necessarily.
Given the complexity, let's stick to one additional data fetch for the example.
But note: the pattern of conditionally rendering a component that uses `use` on a resource is a way to have a Suspense boundary that only suspends for that resource and not for the entire component.
However, the Suspense boundary is around the entire ClientComponent, so if any part of the ClientComponent suspends (including the AdditionalDataComponent) then the fallback shows.
This is acceptable because we want to show a loading indicator for the additional data.
But what if we have multiple independent data fetches in the same client component? We might want to have separate Suspense boundaries for each? Then we would have to move the Suspense boundaries inside the ClientComponent? But we cannot use Suspense inside a client component that is already wrapped by a Suspense boundary? Actually, we can nest Suspense boundaries.
So we could have:
ClientComponent:
return (
<div>
{initialData.map(...)}
<Suspense fallback={<LoadingMore1 />}>
<AdditionalDataComponent1 resource={resource1} />
</Suspense>
<Suspense fallback={<LoadingMore2 />}>
<AdditionalDataComponent2 resource={resource2} />
</Suspense>
</div>
)
But then we are using Suspense inside a client component, which is allowed? Yes, but note that the parent Suspense boundary (the one we wrapped around ClientComponent) will not be triggered by the inner Suspense boundaries. The inner ones will handle their own fallbacks.
However, the ErrorBoundary is around the entire ClientComponent, so it will catch errors in any of the inner components.
So we can have:
Page (Server Component)
|
|-- <ErrorBoundary fallback={<Error />}>
<ClientComponent initialData={initialData} />
</ErrorBoundary>
ClientComponent:
const [resource1, setResource1] = useState(null);
const [resource2, setResource2] = useState(null);
// ... functions to set the resources
return (
<div>
{initialData.map(...)}
<Suspense fallback={<LoadingMore1 />}>
{resource1 && <AdditionalDataComponent1 resource={resource1} />}
</Suspense>
<Suspense fallback={<LoadingMore2 />}>
{resource2 && <AdditionalDataComponent2 resource={resource2} />}
</Suspense>
</div>
)
But note: the conditionally rendering of AdditionalDataComponent1 and AdditionalDataComponent2 (only when resource1/resource2 are set) means that we don't render them until we set the resource. And when we set the resource, the Suspense boundary will start the Suspense and show the fallback until the promise resolves.
This pattern works.
However, we are using `use` inside AdditionalDataComponent1 and AdditionalDataComponent2, which are client components. And we are conditionally rendering them only when the resource is set. This is allowed because the `use` hook is called conditionally only when the component is rendered.
But note: the resource is set by the parent (ClientComponent) and then passed as a prop. The AdditionalDataComponent1 will be rendered only when resource1 is not null, and then it will call `use(resource1)`. This is safe because the component is only rendered when the resource exists.
So, to summarize:
- We have a server component that fetches initial data and passes it to a client component.
- The client component uses the initial data immediately (no suspense for initial data).
- The client component can have multiple asynchronous data fetches (on the client) that are represented by resources (promises).
- For each resource, we conditionally render a child component that uses `use` on that resource, and we wrap that child in a Suspense boundary (which can be in the parent or child, but we put it in the parent for simplicity).
- We wrap the entire client component in an error boundary to catch any errors in the client component and its children.
This pattern allows partial hydration because:
- The initial data is server-rendered and hydrated without a loading state.
- The client-side data fetches are done asynchronously and show their own loading states (via Suspense) only when needed.
Let's write code examples for each part.
Example:
app/page.tsx (Server Component)
import ClientComponent from './ClientComponent';
import { graphql } from '@/lib/graphql'; // hypothetical GraphQL client
export default async function Page() {
const initialData = await graphql(`
query InitialData {
posts(first: 10) {
id
title
content
}
}
`);
return (
<ErrorBoundary fallback={<div>Error loading posts</div>}>
<ClientComponent initialPosts={initialData.posts} />
</ErrorBoundary>
);
}
ClientComponent.tsx (Client Component)
'use client';
import { useState } from 'react';
import AdditionalPosts from './AdditionalPosts';
export default function ClientComponent({ initialPosts }) {
const [posts, setPosts] = useState(initialPosts);
const [page, setPage] = useState(1);
const [resource, setResource] = useState(null);
const loadMore = async () => {
const newResource = fetchMorePosts(page); // returns a promise
setResource(newResource);
// We don't await here because we want to set the resource and then the AdditionalPosts component will suspend.
};
// When the resource resolves, we want to update the posts and reset the resource?
// But note: the AdditionalPosts component will use the resource and then we can update the posts in a useEffect? Or we can have the resource resolve to the new posts and then we update the state.
// Alternatively, we can have the resource be a function that we call in the AdditionalPosts component and then the AdditionalPosts component returns the new posts? But then we need to update the parent state.
// Let's change: the resource is a promise that resolves to the new posts. Then in the AdditionalPosts component, we can call `use(resource)` to get the new posts and then we can update the parent state? But the AdditionalPosts component is a child, so it cannot update the parent state directly.
// We can pass a callback to AdditionalPosts? Or we can lift the state up.
// Alternatively, we can have the loadMore function set a resource that, when resolved, will set the posts in the parent.
// We can do:
// In ClientComponent:
// const loadMore = async () => {
// const newPosts = await fetchMorePosts(page);
// setPosts(prev => [...prev, ...newPosts]);
// setPage(prev => prev + 1);
// }
// But then we are not using Suspense because we are awaiting in the loadMore function and then updating state.
// We want to use Suspense, so we don't await in loadMore. Instead, we set the resource and then the AdditionalPosts component will use that resource and when it resolves, we want to update the posts.
// How can we update the parent state from the child? We can pass an onUpdate callback to AdditionalPosts? But the AdditionalPosts component is the one that uses the resource and gets the data.
// Alternatively, we can have the resource resolve to the new posts and then in the ClientComponent, we can have a useEffect that watches the resource? But the resource is a promise, and we want to know when it resolves.
// Actually, the `use` hook in AdditionalPosts will cause the component to suspend until the promise resolves, and then it will render with the resolved value. We can have AdditionalPosts call a prop function with the new posts? But then we are updating the parent state from the child, which is fine.
// Let's change the pattern:
// In ClientComponent:
// const handleNewPosts = (newPosts) => {
// setPosts(prev => [...prev, ...newPosts]);
// setPage(prev => prev + 1);
// setResource(null); // reset the resource so we can load more again
// }
// Then, in the render:
// {resource && <AdditionalPosts resource={resource} onUpdate={handleNewPosts} />}
// In AdditionalPosts:
// const newPosts = use(resource);
// useEffect(() => {
// onUpdate(newPosts);
// }, [newPosts, onUpdate]);
// But then the AdditionalPosts component will render the newPosts? We might not want to render them in AdditionalPosts, we just want to update the parent's posts.
// Alternatively, we can have AdditionalPosts not render anything and just call onUpdate? But then why use Suspense? We want to show a loading indicator while the resource is pending.
// We can have:
// AdditionalPosts:
// const newPosts = use(resource);
// return null; // or we can render the newPosts in the parent? Actually, the parent is already rendering the posts.
// But then the Suspense boundary will show the fallback while the resource is pending, and then when it resolves, AdditionalPosts will call onUpdate and then the parent will re-render with the new posts.
// However, the AdditionalPosts component will mount and then immediately call onUpdate? We don't want to call onUpdate multiple times.
// Alternatively, we can have the resource be a function that returns a promise, and then in the parent we call that function and set the resource? But then we are not using `use` in the child? We want to use `use` in the child to suspend.
// Let's stick to:
// In the parent, when we want to load more, we set the resource to a promise that resolves to the new posts.
// Then, we render a child that uses that resource and when it resolves, it updates the parent's state via a callback.
// But note: the child component will suspend until the promise resolves, and then it will run the effect to update the parent. Then the parent will re-render with the new posts.
// This seems workable.
// However, we are using an effect to update the parent. But the effect runs after the child has rendered (with the newPosts). We might want to update the parent before the child renders? Actually, the child is just a loader, it doesn't need to render the new posts.
// We can change:
// In AdditionalPosts, we don't render anything, we just call onUpdate in an effect that runs when newPosts changes.
// But then the Suspense boundary will show the fallback until the promise resolves, then the AdditionalPosts component will render (with nothing) and then the effect will run and update the parent, causing a re-render of the parent without the AdditionalPosts component (because we set resource to null in handleNewPosts).
// Steps:
// 1. Click loadMore -> setResource(fetchMorePosts(page))
// 2. Because resource is set, AdditionalPosts is rendered.
// 3. AdditionalPosts uses `use(resource)` and suspends until the promise resolves.
// 4. Suspense boundary shows fallback.
// 5. Promise resolves, AdditionalPosts gets newPosts, then effect runs and calls onUpdate(newPosts).
// 6. onUpdate setsPosts (so parent re-renders with new posts) and setsResource(null).
// 7. Because resource is now null, AdditionalPosts unmounts.
// This works.
// But note: the parent re-renders with the new posts, and the loadMore button is still there.
// However, we are setting resource to null in onUpdate, so the next time we click loadMore, we can set a new resource.
// But what if the fetch fails? The promise will reject and the error will be caught by the error boundary? Yes, because the `use` hook will throw the rejection and the error boundary will catch it.
// So we need to handle errors in the fetchMorePosts function? Actually, if the promise rejects, the `use` hook will throw and the error boundary will catch it.
// But then our onUpdate won't be called. We might want to reset the resource on error? Actually, the error boundary will show the error and then we might have a retry button? That's up to the error boundary.
// Alternatively, we can catch the error in the fetchMorePosts and then set the resource to a rejected promise? Actually, we want the `use` hook to throw so that the error boundary catches it.
// So we don't catch the error in fetchMorePosts.
// Let's code accordingly.
}
return (
<div>
{posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
{resource && (
<Suspense fallback={<div>Loading more posts...</div>}>
<AdditionalPosts resource={resource} onUpdate={handleNewPosts} />
</Suspense>
)}
<button onClick={loadMore}>Load More</button>
</div>
);
AdditionalPosts.tsx
'use client';
import { useEffect } from 'react';
export default function AdditionalPosts({ resource, onUpdate }) {
const newPosts = use(resource); // This will suspend until resource resolves or rejects.
useEffect(() => {
onUpdate(newPosts);
}, [newPosts, onUpdate]);
return null; // We don't render anything, just update the parent.
}
But note: the `use` hook is a React function, so we need to import it.
However, the `use` hook is currently experimental and only available in React 18+ and in frameworks that support it (like Next.js 13+). Also, it's a low-level primitive and might change.
Alternatively, we can use a third-party library that provides a `use` hook for promises? But the React `use` hook is built-in.
But note: the `use` hook is not a hook in the traditional sense? It is a function that must be called at the top level of a component, but it doesn't have the "use" prefix? Actually, it's called `use` and it's a hook.
According to the React documentation, `use` is a hook that must be called at the top level of a component.
So we are using it correctly.
However, the above pattern has a flaw: the AdditionalPosts component will call onUpdate every time newPosts changes, but newPosts is the resolved value of the resource. Since the resource is a promise that resolves only once, it should be fine.
But what if the resource is the same promise object? It will resolve only once.
So it should work.
But note: the parent sets the resource to a new promise every time we click loadMore, so the AdditionalPosts component will unmount and remount? Actually, when we set resource to null, the AdditionalPosts component unmounts. Then when we set a new resource, a new AdditionalPosts component mounts with a new resource.
This is acceptable.
However, we are using an effect in AdditionalPosts to call onUpdate. This effect will run after the component mounts (when newPosts is available). But what if the parent re-renders and the resource is the same? The AdditionalPosts component will not remount because the resource is the same? Actually, when we set resource to a new promise, it's a new object, so the component will remount.
But if we set the same promise object again? We don't, because we set a new promise every time.
So it's safe.
Let's adjust: after the promise resolves, we set resource to null in the parent, so the AdditionalPosts component unmounts. Then when we load more again, we set a new resource and mount a new AdditionalPosts component.
This pattern works for one additional data fetch. For multiple, we can have multiple resources and multiple AdditionalPosts components.
But note: the loadMore function sets only one resource (for the next page). If we want to have multiple independent fetches, we can have multiple resource states and multiple handlers.
This pattern is a starting point.
However, we must note that the `use` hook is still experimental and the API might change.
Also, we are using a client component (AdditionalPosts) that uses `use` and is conditionally rendered. This is allowed because the condition (resource && ...) is outside the component.
But note: the `use` hook must be called unconditionally in the AdditionalPosts component. Since the component is only rendered when resource is truthy, and the `use` hook is called at the top level, it's safe because the component is not rendered when resource is null.
So, to recap the pattern:
Server Component:
- Fetches initial data.
- Renders a client component and passes the initial data as a prop.
- Wraps the client component in an ErrorBoundary (and optionally a Suspense boundary if the client component itself might suspend for something else? But in our pattern, the client component doesn't suspend for the initial data).
Client Component:
- Uses the initial data from the prop.
- Has states for additional resources (promises) and a function to set them (when we want to fetch more).
- Conditionally renders a child component (like AdditionalPosts) for each resource, and wraps each in a Suspense boundary (with its own fallback).
- The child component (AdditionalPosts) uses `use(resource)` to get the data, and then notifies the parent (via a callback) when the data is available.
The parent then updates its state (with the new data) and resets the resource (sets it to null) so that the child component unmounts.
This way, the initial data is rendered without suspense, and the additional data fetches are handled with suspense and error boundaries (the error boundary is on the parent, so it will catch errors in the child).
We can also have the child component handle its own errors with an error boundary? But then we would have to wrap the child in an error boundary inside the Suspense boundary? Actually, we can:
{resource && (
<Suspense fallback={<LoadingMore />}>
<ErrorBoundary fallback={<ErrorLoadingMore />}>
<AdditionalPosts resource={resource} onUpdate={handleNewPosts} />
</ErrorBoundary>
</Suspense>
)}
But then the error boundary is inside the Suspense boundary. If the AdditionalPosts component throws an error (including from the `use` hook), it will be caught by the inner error boundary? Actually, the `use` hook throws a promise that is caught by the nearest Suspense boundary. So the error from the `use` hook (if the promise rejects) will be caught by the Suspense boundary, not the error boundary.
Wait, in React 18, when a promise rejects, the `use` hook throws the rejection and it is caught by the nearest Suspense boundary. So we don't need an error boundary for the `use` hook? Actually, if the promise rejects, the Suspense boundary will show the fallback? No, the Suspense boundary is for pending promises. For rejected promises, it will throw and be caught by the nearest error boundary? Let me check:
According to the React documentation, when a promise rejects, the `use` hook will throw the rejection and it will be caught by the nearest error boundary, not Suspense. Suspense is only for pending.
So we need an error boundary to catch the rejection.
But in our pattern, we have an error boundary around the entire client component. That should catch the rejection from the `use` hook in AdditionalPosts.
However, the rejection will cause the entire client component to error? Actually, the error boundary around the client component will catch the error and show the fallback for the entire client component? That might be too broad.
We might want to catch the error only for the additional data fetch and not for the entire component.
So we can wrap the AdditionalPosts component in an error boundary inside the Suspense boundary? But note: the `use` hook throws the rejection, which is an error, and it will be caught by the nearest error boundary. If we put an error boundary inside the Suspense boundary, it will catch the rejection and show its own fallback, and the Suspense boundary will not be involved because the error boundary caught the error.
But wait: the `use` hook throws a promise rejection, which is an error, and it will be caught by the nearest error boundary. The Suspense boundary only catches pending promises? Actually, Suspense for data fetching (with `use`) works by catching the promise that is thrown by `use` and then showing the fallback until the promise resolves. If the promise rejects, it throws the error and then the error boundary catches it.
So the flow:
- `use(promise)` throws the promise (if pending) -> Suspense catches it and shows fallback.
- When the promise resolves, `use` returns the value and the component re-renders.
- If the promise rejects, `use` throws the rejection -> the error boundary catches it.
So we need both Suspense and ErrorBoundary for the same resource? We can wrap the AdditionalPosts component in an ErrorBoundary and then the Suspense boundary? Actually, the order matters.
We want:
- While the promise is pending, show the Suspense fallback.
- If the promise rejects, show the ErrorBoundary fallback.
So we need to wrap the AdditionalPosts component with both:
<ErrorBoundary fallback={<Error />}>
<Suspense fallback={<Loading />}>
<AdditionalPosts resource={resource} onUpdate={handleNewPosts} />
</Suspense>
</ErrorBoundary>
But note: the ErrorBoundary will catch errors in the Suspense boundary? Actually, the Suspense boundary will catch the pending promise and show the fallback, but when the promise rejects, the `use` hook will throw and that throw will be caught by the ErrorBoundary because the ErrorBoundary is the parent of the Suspense boundary? No, the ErrorBoundary is the parent of the Suspense boundary, so the throw from `use` (which is inside AdditionalPosts, which is inside Suspense) will propagate up to the ErrorBoundary and the Suspense boundary will not catch it because it's not a pending promise anymore, it's an error.
Actually, the Suspense boundary only catches the pending promise. When the promise rejects, the `use` hook throws the error and the error will propagate to the ErrorBoundary.
So the above structure is correct.
But wait: the Suspense boundary is inside the ErrorBoundary. The ErrorBoundary will catch any error in its children, including the Suspense boundary. But the Suspense boundary itself doesn't throw when the promise is pending? It catches the pending promise and shows the fallback. When the promise rejects, the `use` hook throws and that throw will go through the Suspense boundary (because the Suspense boundary doesn't catch errors, it only catches the pending promise) and then the ErrorBoundary will catch it.
So we are safe.
However, if the AdditionalPosts component throws an error that is not from the `use` hook (like a bug), the ErrorBoundary will catch it too.
So we have:
Page (Server Component)
|
|-- <ErrorBoundary fallback={<div>Error in the whole client component</div>}>
<ClientComponent initialPosts={initialPosts} />
</ErrorBoundary>
ClientComponent:
return (
<div>
{posts.map(...)}
{resource && (
<ErrorBoundary fallback={<div>Error loading more posts</div>}>
<Suspense fallback={<div>Loading more posts...</div>}>
<AdditionalPosts resource={resource} onUpdate={handleNewPosts} />
</Suspense>
</ErrorBoundary>
)}
<button onClick={loadMore}>Load More</button>
</div>
)
This gives us:
- The initial data is rendered without any loading state.
- When loading more, we show a loading indicator (from Suspense) and if the fetch fails, we show an error (from the inner ErrorBoundary) without affecting the rest of the component.
But note: the inner ErrorBoundary only covers the AdditionalPosts component. If there's an error in the rest of the ClientComponent (like in the initial posts rendering), the outer ErrorBoundary will catch it.
This seems like a good pattern.
However, we must note that the `use` hook is experimental and might not be available in all React versions. Also, this pattern is specific to React 18+.
Let's adjust for a more stable approach if `use` is not available:
We can use a third-party library that provides a `use` hook for promises? Or we can use a state and effect to handle the promise? But then we lose the built-in Suspense integration.
Alternatively, we can use the `use` hook from 'react' if we are using React 18. Otherwise, we might have to use a different pattern.
Given the requirement of using Suspense, we assume React 18.
So the final pattern:
- Server component fetches initial data and passes to client component.
- Client component uses the initial data and has states for additional resources.
- For each additional resource, we conditionally render a child component that uses `use(resource)` and is wrapped in both Suspense and ErrorBoundary.
- The child component, when the resource resolves, calls a callback to update the parent's state and then the parent clears the resource.
This pattern allows partial hydration because the initial data is server-rendered and hydrated without a loading state, and the client-side data fetches are handled with Suspense and Error Boundaries independently.
We can extend this pattern for multiple independent data fetches in the same client component.
However, note that the `use` hook is designed for server components to pass resources to client components. But we are creating the resource in the client component and then using it in a child component. This is allowed because the resource is created in the client component and then passed to the child.
But the `use` hook is intended for resources that are created in a server component? Actually, the React documentation says that `use` can be used in client components for resources that are created in server components and passed down. But it doesn't forbid creating a resource in the client component and then using it in a child? We are creating the resource (a promise) in the parent client component and then passing it to the child, and the child uses `use` on that promise. This should work because the promise is already created and the child is using it.
However, the React documentation says that `use` should be called with a resource that is a promise that was created in a server component? I think it's just a recommendation because server components can create the resource and then the client component can use it without having to create the promise on the client (which might cause a mismatch). But in our case, we are creating the promise on the client and then using it in a child client component. This is acceptable because both are client components.
But note: the promise is created in the parent and then passed to the child. The child uses `use` and suspends. This is exactly how `use` is intended to be used? Actually, the `use` hook is designed to work with resources that are created in a server component and then passed to a client component, but it can also be used with resources created in a client component? The documentation doesn't explicitly forbid it.
However, there is a catch: the promise must be the same across renders? We are creating a new promise every time we set the resource. That's okay because we are setting a new resource and then the child will use that new promise.
So it should work.
Let's code accordingly.
But note: the `use` hook is not stable and might change. This pattern is based on the current React 18 behavior.
If we are using Next.js 13, they have a `use` hook that is stable? Actually, Next.js 13 uses React 18 and the `use` hook is available.
So we proceed.
One more thing: the `use` hook is not a hook that we can conditionally call. In the AdditionalPosts component, we call `use(resource)` unconditionally. But the component is only rendered when resource is truthy, so it's safe.
We are good.
Let's write the code for the example.
However, note that the `use` hook is not yet stable and the API might change. Also, we are using TypeScript, we might need to adjust types.
We'll write in JavaScript for simplicity.
If we are using TypeScript, we need to type the resource as a Promise of the data.
Let's write:
// types.ts
export type Post = {
id: string;
title: string;
content: string;
};
Then in AdditionalPosts:
import { Post } from './types';
interface AdditionalPostsProps {
resource: Promise<Post[]>;
onUpdate: (posts: Post[]) => void;
}
export default function AdditionalPosts({ resource, onUpdate }: AdditionalPostsProps) {
const newPosts = use(resource); // This will be Post[] when resolved.
useEffect(() => {
onUpdate(newPosts);
}, [newPosts, onUpdate]);
return null;
}
And in ClientComponent:
const [resource, setResource] = useState<Promise<Post[]> | null>(null);
const loadMore = async () => {
setResource(fetchMorePosts(page));
};
const handleNewPosts = (newPosts: Post[]) => {
setPosts(prev => [...prev, ...newPosts]);
setPage(prev => prev + 1);
setResource(null);
};
And fetchMorePosts:
async function fetchMorePosts(page: number): Promise<Post[]> {
const response = await fetch(`/api/posts?page=${page}&limit=10`);
if (!response.ok) {
throw new Error('Failed to fetch more posts');
}
return response.json();
}
But note: the fetchMorePosts function returns a promise that might reject. The `use` hook will throw that rejection and the error boundary will catch it.
This pattern should work.
However, we are using `fetch` in the client component. We might want to use a GraphQL client? The same pattern applies: the function returns a promise that resolves to the data.
So we have a pattern for partial hydration with GraphQL (or any data fetching) that uses:
- Server component for initial data.
- Client component for interactive parts and client-side data fetching.
- Suspense for showing loading states for client-side data.
- Error boundaries for catching errors in client-side data.
And we avoid showing a loading state for the initial data because it's already fetched on the server.
This is a partial hydration pattern.
Let me know if you have any questions.</think>
I'll design a comprehensive partial hydration pattern for a GraphQL application combining React Server Components, Client Components, Suspense, and Error Boundaries. This pattern optimizes initial load performance while maintaining interactivity where needed.
Architecture Overview
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ Server Page │───▶│ Server Component │───▶│ Client Component │
│ (RSC) │ │ (Static Parts) │ │ (Interactive) │
└─────────────────┘ └─────────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ GraphQL Query │ │ Static HTML/JSON │ │ Hydration │
│ (Server-side) │ │ (No JS) │ │ + Data Fetch │
└─────────────────┘ └─────────────────────┘ └─────────────────┘
1. File Structure
app/
├── page.tsx # Server Component (Main page)
├── components/
│ ├── UserProfile/
│ │ ├── UserProfile.tsx # Server Component
│ │ ├── UserAvatar.tsx # Client Component (interactive)
│ │ ├── UserStats.tsx # Client Component (Suspense)
│ │ └── UserActivity.tsx # Client Component (Error Boundary)
│ ├── PostFeed/
│ │ ├── PostFeed.tsx # Server Component
│ │ ├── PostCard.tsx # Client Component
│ │ └── CreatePost.tsx # Client Component (Form)
│ └── Dashboard/
│ ├── Dashboard.tsx # Server Component
│ ├── StatsCard.tsx # Client Component (Suspense)
│ └── RecentActivity.tsx # Client Component
2. Core Implementation
2.1 GraphQL Client Setup
// lib/graphql-client.ts
import { GraphQLClient, gql } from 'graphql-request';
const client = new GraphQLClient(process.env.NEXT_PUBLIC_GRAPHQL_URL!);
export const getServerSideGraphQLClient = () => {
// Server-side client with SSR support
return client;
};
export const GET_USER_DATA = gql`
query GetUserData($id: ID!) {
user(id: $id) {
id
name
avatar
stats {
posts
followers
following
}
recentActivity {
id
type
timestamp
}
}
}
`;
export const GET_FEED_POSTS = gql`
query GetFeedPosts($cursor: String) {
posts(first: 10, after: $cursor) {
edges {
node {
id
title
content
author {
id
name
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
2.2 Main Server Component Page
// app/page.tsx
import { Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { getServerSideGraphQLClient, GET_USER_DATA } from '@/lib/graphql-client';
import UserProfile from './components/UserProfile/UserProfile';
import PostFeed from './components/PostFeed/PostFeed';
// Error Fallback Component
function ErrorFallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
return (
<div className="p-4 border border-red-200 bg-red-50 rounded-lg">
<h2 className="text-red-800 font-semibold">Something went wrong</h2>
<p className="text-red-600">{error.message}</p>
<button
onClick={resetErrorBoundary}
className="mt-2 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
>
Try again
</button>
</div>
);
}
// Loading Fallback Component
function PageLoadingFallback() {
return (
<div className="animate-pulse space-y-4">
<div className="h-8 bg-gray-200 rounded w-1/4"></div>
<div className="h-64 bg-gray-200 rounded"></div>
<div className="h-64 bg-gray-200 rounded"></div>
</div>
);
}
export default async function HomePage() {
// Server-side data fetching
const client = getServerSideGraphQLClient();
const userId = 'current-user-id'; // Get from session/auth
try {
const userData = await client.request(GET_USER_DATA, { id: userId });
return (
<div className="container mx-auto px-4 py-8">
{/* Error Boundary for main sections */}
<ErrorBoundary FallbackComponent={ErrorFallback}>
<Suspense fallback={<PageLoadingFallback />}>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Left Column - User Profile (Partially Hydrated) */}
<div className="lg:col-span-1">
<UserProfile initialData={userData.user} />
</div>
{/* Right Column - Post Feed (Partially Hydrated) */}
<div className="lg:col-span-2">
<PostFeed />
</div>
</div>
</Suspense>
</ErrorBoundary>
</div>
);
} catch (error) {
// Server-side error handling
return (
<div className="container mx-auto px-4 py-8">
<ErrorFallback
error={error instanceof Error ? error : new Error('Failed to load page')}
resetErrorBoundary={() => window.location.reload()}
/>
</div>
);
}
}
2.3 Server Component with Partial Hydration
// components/UserProfile/UserProfile.tsx
'use client';
import { useState, useEffect } from 'react';
import UserAvatar from './UserAvatar';
import UserStats from './UserStats';
import UserActivity from './UserActivity';
interface User {
id: string;
name: string;
avatar: string;
stats: {
posts: number;
followers: number;
following: number;
};
recentActivity: Array<{
id: string;
type: string;
timestamp: string;
}>;
}
interface UserProfileProps {
initialData: User;
}
export default function UserProfile({ initialData }: UserProfileProps) {
const [user, setUser] = useState(initialData);
const [isRefreshing, setIsRefreshing] = useState(false);
// Client-side revalidation (optional)
const refreshUserData = async () => {
setIsRefreshing(true);
try {
// Client-side fetch for real-time updates
const response = await fetch('/api/user/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: user.id })
});
const freshData = await response.json();
setUser(freshData);
} finally {
setIsRefreshing(false);
}
};
return (
<div className="bg-white rounded-xl shadow-md p-6">
{/* Interactive Avatar (Client Component) */}
<UserAvatar
src={user.avatar}
alt={user.name}
onChangeAvatar={refreshUserData}
/>
<h2 className="text-2xl font-bold mt-4">{user.name}</h2>
{/* Suspense Boundary for Stats */}
<div className="mt-6">
<h3 className="text-lg font-semibold mb-3">Statistics</h3>
<Suspense fallback={<div className="h-20 bg-gray-100 animate-pulse rounded" />}>
<UserStats stats={user.stats} />
</Suspense>
</div>
{/* Error Boundary for Activity */}
<div className="mt-6">
<h3 className="text-lg font-semibold mb-3">Recent Activity</h3>
<ErrorBoundary
fallback={<div className="p-4 text-red-600">Failed to load activity</div>}
>
<UserActivity
activities={user.recentActivity}
refresh={isRefreshing}
onRefresh={refreshUserData}
/>
</ErrorBoundary>
</div>
<button
onClick={refreshUserData}
disabled={isRefreshing}
className="mt-4 w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-blue-300"
>
{isRefreshing ? 'Refreshing...' : 'Refresh Data'}
</button>
</div>
);
}
2.4 Client Component with Suspense
// components/UserProfile/UserStats.tsx
'use client';
import { use } from 'react';
interface Stats {
posts: number;
followers: number;
following: number;
}
interface UserStatsProps {
stats: Stats;
}
// This component can fetch additional data if needed
async function fetchExtendedStats(userId: string): Promise<Stats> {
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 1000));
// In reality, this would be a GraphQL query
return {
posts: Math.floor(Math.random() * 100),
followers: Math.floor(Math.random() * 1000),
following: Math.floor(Math.random() * 500)
};
}
export default function UserStats({ stats }: UserStatsProps) {
// Example: Could fetch more detailed stats here
// const extendedStats = use(fetchExtendedStats('user-id'));
return (
<div className="grid grid-cols-3 gap-4">
<div className="text-center p-3 bg-blue-50 rounded-lg">
<div className="text-2xl font-bold text-blue-600">{stats.posts}</div>
<div className="text-sm text-gray-600">Posts</div>
</div>
<div className="text-center p-3 bg-green-50 rounded-lg">
<div className="text-2xl font-bold text-green-600">{stats.followers}</div>
<div className="text-sm text-gray-600">Followers</div>
</div>
<div className="text-center p-3 bg-purple-50 rounded-lg">
<div className="text-2xl font-bold text-purple-600">{stats.following}</div>
<div className="text-sm text-gray-600">Following</div>
</div>
</div>
);
}
2.5 Client Component with Error Boundary
// components/UserProfile/UserActivity.tsx
'use client';
import { useState, useEffect } from 'react';
interface Activity {
id: string;
type: string;
timestamp: string;
}
interface UserActivityProps {
activities: Activity[];
refresh: boolean;
onRefresh: () => void;
}
export default function UserActivity({ activities, refresh, onRefresh }: UserActivityProps) {
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (refresh) {
// Simulate potential error during refresh
if (Math.random() > 0.8) {
setError(new Error('Failed to fetch activity'));
} else {
setError(null);
}
}
}, [refresh]);
if (error) {
throw error; // Will be caught by ErrorBoundary
}
const getActivityIcon = (type: string) => {
switch (type) {
case 'POST': return '📝';
case 'LIKE': return '❤️';
case 'COMMENT': return '💬';
default: return '🔔';
}
};
return (
<div className="space-y-3">
{activities.length === 0 ? (
<p className="text-gray-500 text-center py-4">No recent activity</p>
) : (
activities.map(activity => (
<div key={activity.id} className="flex items-center gap-3 p-3 border rounded-lg">
<span className="text-xl">{getActivityIcon(activity.type)}</span>
<div className="flex-1">
<p className="font-medium capitalize">{activity.type}</p>
<p className="text-sm text-gray-500">
{new Date(activity.timestamp).toLocaleString()}
</p>
</div>
</div>
))
)}
</div>
);
}
2.6 Client Component with GraphQL Mutation
// components/PostFeed/CreatePost.tsx
'use client';
import { useState } from 'react';
import { graphql } from 'graphql-request';
const CREATE_POST = graphql`
mutation CreatePost($content: String!) {
createPost(content: $content) {
id
content
createdAt
}
}
`;
export default function CreatePost() {
const [content, setContent] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim()) return;
setIsSubmitting(true);
setError(null);
try {
const response = await fetch('/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: CREATE_POST.loc?.source.body,
variables: { content }
})
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
setContent('');
// Optionally trigger a refresh of the feed
window.dispatchEvent(new CustomEvent('post-created', { detail: result.data.createPost }));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create post');
} finally {
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit} className="mb-6">
<div className="mb-4">
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="What's on your mind?"
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
rows={3}
/>
</div>
{error && (
<div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">
{error}
</div>
)}
<button
type="submit"
disabled={isSubmitting || !content.trim()}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-blue-300 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Posting...' : 'Post'}
</button>
</form>
);
}
2.7 Post Feed with Streaming/Suspense
// components/PostFeed/PostFeed.tsx
'use client';
import { Suspense, useEffect, useState } from 'react';
import PostCard from './PostCard';
import CreatePost from './CreatePost';
import { GET_FEED_POSTS } from '@/lib/graphql-client';
// Component that fetches and streams posts
async function PostList() {
// This would typically use a client-side GraphQL client like Apollo
// For simplicity, using fetch directly
const response = await fetch('/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: GET_FEED_POSTS.loc?.source.body,
variables: {}
})
});
const { data } = await response.json();
if (!data?.posts?.edges) {
throw new Error('Failed to load posts');
}
return (
<div className="space-y-4">
{data.posts.edges.map(({ node }: any) => (
<PostCard key={node.id} post={node} />
))}
{data.posts.pageInfo.hasNextPage && (
<button className="w-full py-3 border rounded-lg hover:bg-gray-50">
Load More
</button>
)}
</div>
);
}
export default function PostFeed() {
const [showCreatePost, setShowCreatePost] = useState(false);
useEffect(() => {
// Listen for post creation events
const handlePostCreated = () => {
// Optionally refresh the feed or update cache
window.location.reload(); // Simple approach
};
window.addEventListener('post-created', handlePostCreated);
return () => window.removeEventListener('post-created', handlePostCreated);
}, []);
return (
<div className="bg-white rounded-xl shadow-md p-6">
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold">Feed</h2>
<button
onClick={() => setShowCreatePost(!showCreatePost)}
className="px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200"
>
{showCreatePost ? 'Cancel' : 'New Post'}
</button>
</div>
{showCreatePost && <CreatePost />}
{/* Suspense boundary for streaming posts */}
<Suspense fallback={
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<div key={i} className="animate-pulse border rounded-lg p-4">
<div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
<div className="h-3 bg-gray-200 rounded w-full mb-1"></div>
<div className="h-3 bg-gray-200 rounded w-5/6"></div>
</div>
))}
</div>
}>
<ErrorBoundary fallback={<div>Failed to load posts</div>}>
<PostList />
</ErrorBoundary>
</Suspense>
</div>
);
}
2.8 Types and Utilities
// types/graphql.ts
export interface GraphQLResponse<T> {
data?: T;
errors?: Array<{
message: string;
locations?: Array<{ line: number; column: number }>;
path?: Array<string>;
}>;
}
export interface PaginatedResponse<T> {
edges: Array<{ node: T }>;
pageInfo: {
hasNextPage: boolean;
endCursor: string | null;
};
}
3. API Route for Client-side GraphQL
// app/api/graphql/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getServerSideGraphQLClient } from '@/lib/graphql-client';
export async function POST(request: NextRequest) {
try {
const { query, variables } = await request.json();
const client = getServerSideGraphQLClient();
const data = await client.request(query, variables);
return NextResponse.json({ data });
} catch (error) {
console.error('GraphQL Error:', error);
return NextResponse.json(
{ errors: [{ message: 'Internal server error' }] },
{ status: 500 }
);
}
}
4. Key Principles of This Pattern
Hydration Strategy
- Server-First Rendering: Initial page load gets SSR HTML with critical data
- Progressive Hydration: Client components hydrate independently
- Selective Hydration: Non-interactive parts remain static (no hydration cost)
Suspense Boundaries
- Wrap client-side data fetching components
- Show loading states only for async client operations
- Don't wrap server-fetched data (already present)
Error Boundaries
- Wrap individual interactive components
- Provide graceful degradation for failed client fetches
- Isolate failures to prevent total page crash
Data Flow
Server Data → Props → Client Component → (Optional Client Fetch) → UI
↓ ↓ ↓
Static Hydrated Suspended
5. Performance Optimizations
// Use this pattern for very expensive client computations
'use client';
import { useMemo, useCallback } from 'react';
export function ExpensiveComponent({ data }: { data: any }) {
// Memoize expensive computations
const processedData = useMemo(() => {
return data.map(/* expensive operation */);
}, [data]);
// Memoize callbacks
const handleClick = useCallback((id: string) => {
// expensive operation
}, []);
return <div>{/* render */}</div>;
}
6. When to Use Each Pattern
| Scenario | Server Component | Client Component | Suspense | Error Boundary |
|---|
| Static content (headers, footers) | ✅ | ❌ | ❌ | ❌ |
| SEO-critical content | ✅ | ❌ | ❌ | ❌ |
- Interactive UI (buttons, forms) | ❌ | ✅ | ❌ | ✅ |
- Data that changes frequently | ❌ | ✅ | ✅ | ✅ |
- Real-time updates | ❌ | ✅ | ✅ | ✅ |
- Complex visualizations | ❌ | ✅ | ✅ | ✅ |
7. Best Practices
- Start with Server Components: Default to server components, extract to client only when needed
- Minimize Client Components: Each client component adds hydration cost
- Granular Error Boundaries: Wrap individual interactive components, not entire pages
- ** thoughtful Suspense Placement**: Only wrap async client operations, not server-fetched data
- Avoid "Hydration Mismatch": Ensure server and client render identical initial HTML
- Use
useEffect for side effects: Not for data fetching (use Suspense instead)
- Implement proper loading states: Provide meaningful fallbacks in Suspense boundaries
This pattern gives you:
- Fast initial load (server-rendered)
- Progressive interactivity (partial hydration)
- Resilient UI (error boundaries)
- Smooth UX (suspense boundaries)
- Optimal caching (server-side data freshness)