Client-Side Rendering (CSR)
Client-Side Rendering is the traditional approach where the browser downloads JavaScript and renders the page. In Next.js, this is the default behavior when you don't use server-side data fetching methods.
Think of CSR like assembling furniture at home. You get the pieces (JavaScript) and instructions, then put everything together yourself. It takes some time, but once assembled, everything works smoothly.
How CSR Works
With CSR, the browser receives a minimal HTML shell and JavaScript files. The JavaScript then takes over and renders the complete page.
Here's the typical flow:
1. Browser requests the page
2. Server sends a basic HTML structure with script tags
3. Browser downloads JavaScript files
4. JavaScript executes and renders the page content
5. Page becomes interactive
This approach is simpler but can result in slower initial page loads, especially on slower connections.
Implementing CSR in Next.js
In Next.js, you can use client-side rendering by fetching data in your components using React hooks. The 'use client' directive marks a component as a client component.
'use client';
import { useState, useEffect } from 'react';
export default function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, [userId]);
if (loading) return <div>Loading...</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
This component fetches data on the client side after it mounts. The data isn't available during server rendering.
When to Use CSR
CSR is perfect for highly interactive pages that need real-time updates. Chat applications, dashboards with live data, and interactive tools work great with CSR.
It's also useful when the content is personalized and can't be cached. User settings, shopping carts, and search results often use CSR.
However, CSR isn't ideal for SEO because search engines may not execute JavaScript properly. For public-facing content, consider SSR or SSG.
CSR vs SSR vs SSG
Each rendering strategy has its place:
CSR: Best for interactive, personalized content. Simple to implement but slower initial loads.
SSR: Great for SEO and dynamic content. Faster initial loads but requires server resources.
SSG: Blazing fast performance. Perfect for content that doesn't change often.
Next.js makes it easy to mix these approaches. Use CSR for your dashboard, SSR for your blog's homepage, and SSG for your documentation.