Introduction
- Next.js v14 introduces powerful routing and rendering capabilities with its App Router and Pages Router. Understanding Client-Side Rendering (CSR) and Server-Side Rendering (SSR) is crucial for optimizing the performance and user experience of your application.
Client-Side Rendering (CSR)
- CSR renders content in the browser using JavaScript. It’s great for dynamic interactions and reducing server load, but may affect initial load time.
Advantages:
- Faster subsequent page loads
- Rich client-side interactions
- Reduces server load
- Smoother transitions between pages
Disadvantages:
- Slower initial load time
- Dependent on JavaScript being enabled in the browser
- Can impact SEO negatively
Example: App Router (CSR)
"use client"
// app/page.js
import { useEffect, useState } from 'react';
const Page = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data ? <div>{data.content}</div> : <div>Loading...</div>}
</div>
);
};
export default Page;
Example: Pages Router (CSR)
"use client"
// pages/index.js
import { useEffect, useState } from 'react';
export default function Home() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data ? <div>{data.content}</div> : <div>Loading...</div>}
</div>
);
}
Server-Side Rendering (SSR)
- SSR renders content on the server and sends a fully populated HTML page to the client. This improves initial load time and SEO but can increase server load.
Advantages:
- Better SEO
- Faster initial page load
- Content is accessible without JavaScript
Disadvantages:
- Increased server load
- Slower subsequent page loads compared to CSR
- More complex to implement
Example: App Router (SSR)
// app/page.js
const Page = async() => {
const res = await fetch('/api/data');
const data = await res.json();
return (
<div>
<div>{data.content}</div>
</div>
);
};
export default Page;
Example: Pages Router (SSR)
// pages/index.js
export async function getServerSideProps() {
const res = await fetch('http://localhost:3000/api/data');
const data = await res.json();
return {
props: {
data,
},
};
}
export default function Home({ data }) {
return (
<div>
<div>{data.content}</div>
</div>
);
}
What is "use client"?
- In Next.js, "use client" is a directive that indicates that a component or page should be rendered on the client side. This is particularly useful for components that rely heavily on client-side interactivity or when you want to explicitly control rendering behavior.
Comments
(1)