The Two-Pass Render Pattern
What you'll learn: How to use useState with useEffect to render safely on the server, then update the UI after hydration completes.
The Core Problem
You've seen that hydration mismatches occur when server HTML differs from the initial client render. But sometimes you need browser-only data (like window.innerWidth or localStorage) — data that simply doesn't exist on the server.
The Two-Pass Solution
The two-pass render pattern solves this by rendering in two stages:
- First pass (server + initial client): Render a safe, static default
- Second pass (after hydration): Update to the real, browser-specific value
Here's the pattern:
function WindowWidth() {
const [width, setWidth] = useState(null); // Safe default
useEffect(() => {
// Only runs on client, after hydration
setWidth(window.innerWidth);
}, []);
// First pass renders this on both server and client
if (width === null) {
return <div>Loading width...</div>;
}
// Second pass (client-only) renders the real value
return <div>Width: {width}px</div>;
}
Why This Works
- Server render:
widthisnull, renders "Loading width..." - Initial client render (hydration):
widthis stillnull, renders "Loading width..." — no mismatch! - useEffect fires: Sets
widthto real value, triggers re-render - Second render: Shows actual width
The first render is identical everywhere. The second render happens after React has already hydrated, so mismatches are impossible.
The Tradeoff
You show a loading state briefly, but you avoid hydration errors entirely. Think of it like a loading screen that bridges the server-client gap.
Key Takeaway: The two-pass render pattern uses useState with a safe default and useEffect to update after hydration, ensuring the server and initial client renders always match.