Back to React Experiments
CSR (Client-Side Rendering)
Completed
Render content in the browser using JavaScript, supporting real-time data and high interactivity
Difficulty:Beginner
Est. Time:20 mins
Next.js
React
JavaScript
Interactive
Core Features:
Browser-side Rendering
Real-time Data Fetching
High Interactivity
User-specific Content
🌐 CSR (Client-Side Rendering) Example
This page is rendered in the browser, with data fetched via client-side API calls.
Client Component
Runtime Rendering
Dynamic Data
Interactive
Real-time Product List
💡 CSR Core Features
- Client-side Rendering: Data is fetched and rendered in the browser via JavaScript
- Real-time Data: Fresh data is fetched on each visit (click "Refresh Data" to see changes)
- High Interactivity: Can use React Hooks and browser APIs
- Slower Initial Load: Must load JavaScript, fetch data, then render
- Poor SEO: Search engine crawlers see blank pages
🔧 How to Use
1. Create Client Component:
'use client'; // Must add this line!
import { useState, useEffect } from 'react';
export default function ProductList() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Fetch data on the client
fetch('https://api.example.com/products')
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
return <div>{/* Render data */}</div>;
}2. Key Points:- Must add
'use client'directive at the top of the file - Can use
useState、useEffectand other Hooks - Can access
window、documentand other browser APIs - Data is fetched fresh on every page load
⚖️ CSR vs SSG Comparison
| Feature | CSR | SSG |
|---|---|---|
| Render Timing | Browser runtime | Build time |
| Data Freshness | Real-time fresh | Build-time data |
| Initial Load | Slower (JS + data) | Fastest (pure HTML) |
| SEO | Poor | Excellent |
| Use Cases | Dashboards, real-time data | Blogs, docs, product pages |
📚 Learning Resources
💡 Learning Suggestion:
After completing the experiment, view the page source (right-click → View Page Source) and compare the HTML content differences between SSG and CSR to understand how they work.