This content originally appeared on DEV Community and was authored by Harsh Singh
Hi Guys! Welcome back to my blog with mastering nextjs with me.
Today we'll get to know about Server-Side and Client-Side Components in Next.js. It is a particularly fun topic to do some research about as the concept is rather simple but hides many complexities behind the simple use of these components.
Understanding the key differences and where to use these components will help you to building optimized, performant, and SEO-friendly applications and fully utilize the powerfull features that Next.js provide. In this blog, we’ll dive deep into these two types of components, explore their key differences, and discuss when to use each.
What are Server-Side Components?
Every Component that is made in Next.js is by default is a Server-Side Component
// app/page.jsx
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
if(data){
return <main></main>
}
else{
notFound()
}
}
Next.js provide the native fetch feature in which there are many options to revalidate the cache or do not store the cache at all. You can read more about it here. Link.
In the Server-Side Component, the component is rendered on the server and whatever data needs to be fetched or API calls needed to be made happens on the server side. Complete HTML data is generated on the server and sent to the browser to load.
Once the HTML is loaded, JavaScript takes over to "hydrate" the page, making it interactive by attaching event listeners and enabling any dynamic client-side functionality.
Advantages
- Improved SEO: Since the content is pre-rendered on server, makes it easier for search engines to crawl and index the page.
- Faster Initial Load Time:Users receive a fully-rendered page immediately, which reduces the time it takes for them to see and interact with the content.
- Better Performance on Slow Networks:Since the HTML is pre-rendered, users on slower networks can see the content faster, even if the client-side JavaScript takes longer to load.
Some Limitations
- Increased Server Load: Since the server handles rendering, it can become a bottleneck under heavy traffic.
- Slower Interactions: After the initial page load, interactions might be slower compared to fully client-rendered applications, especially if frequent server round-trips are required.
What are Client-Side Components?
Every component in Next.js is Server Component but after adding "use client" on top of the component it becomes a Client component.
After making it a client component, it will have access to all the browser functionalities like the window object, setTimeOut etc.
"use client"
import { useEffect, useState } from 'react';
export default function ClientSideComponent() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/data')
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
return (
<div>
<h1>Client-Side Component Example</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
In this when request is made to the server, it responds with the minimal amount of HTML or HTML shell like a div which happens in react and that gets loaded after that all the javasript files are loaded and executed and all the API calls and rendering of the jsx components occurs at this time and we will get a fully interactive page.
User can interact with the page with reloading it.
Advantages
- Rich Interactivity: Ideal for building highly interactive user interfaces. They enable real-time updates, animations, and smooth transitions without requiring a full page reload.
- Better User Experience for Single-Page Applications (SPAs): Since the content is rendered on the client, users experience a seamless flow as they navigate through different parts of the application. This is a common approach in SPAs, where only a portion of the page updates in response to user interactions.
- Reduced Server Load: By offloading rendering tasks to the client, CSR reduces the server's workload.
- Flexibility in Data Fetching: CSR allows developers to fetch data on-demand, meaning you can load data only when needed, based on user interactions.
Some Limitations
- Slower Initial Load Time : Slower load time as the page is rendered on the browser after the javascript is loaded on to the browser.
- SEO Challenges: As you have guessed it, Since the page is not pre-rendered hence it is difficult for search engines to crawl and index the pages.
- Potential for Poor User Experience on Slow Networks: Users on slow networks may experience delays while waiting for JavaScript to load and execute, leading to a suboptimal user experience.
Key Differences Between Server-Side and Client-Side Components
Rendering:
- Server-Side:Rendered on the server before the HTML is sent to the client's browser.
- Client-Side:Rendered directly in the client's browser after the initial HTML is loaded.
Initial Load Time
- Server-Side: Typically faster,server sends pre-rendered HTML page to browser.
- Client-Side: May have slower initial load, JS files are downloaded and then executed.
SEO
- Server-Side: Better, as easy to crawl pre-rendered HTML pages.
- Client-Side: Challenging, as content is rendered dynamically on browser.
Interactivity
- Server-Side: Initial page is fully rendered and static, with interactivity added after the page is hydrated by JavaScript.
- Client-Side: Highly interactive from the start, with dynamic content that can change based on user actions or real-time data.
Data Fetching
- Server-Side: Fetched on the server, component rendered with complete content.
- Client-Side: Fetched on the Client/Browser, may lead to performance issues on slower network.
Many Client components can contain Server Components and Vice versa
Use Cases
Server-Side Components: Ideal for content-heavy, SEO-focused applications where initial load time is critical, such as blogs, e-commerce sites, and marketing pages.
Client-Side Components: Best for highly interactive applications, single-page applications (SPAs), or scenarios where content needs to be frequently updated or personalized.
This content originally appeared on DEV Community and was authored by Harsh Singh
Harsh Singh | Sciencx (2024-08-04T21:12:56+00:00) Mastering Next.js: Decoding Server-Side and Client-Side Components. Retrieved from https://www.scien.cx/2024/08/04/mastering-next-js-decoding-server-side-and-client-side-components/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.