What is Server Component in Next.js: Simple Explanation and Example
server component in Next.js is a React component that runs only on the server, not in the browser. It helps improve performance by rendering content on the server and sending ready HTML to the client, reducing JavaScript sent to users.How It Works
Think of a server component like a chef in a restaurant kitchen. The chef prepares the dish (renders the component) behind the scenes (on the server), and then the waiter brings the finished dish (HTML) to the customer (browser). This means the customer gets the meal faster without waiting for the chef to cook in front of them.
In Next.js, server components run only on the server during the page request. They can fetch data directly from databases or APIs without exposing secrets to the browser. The server then sends the fully rendered HTML to the browser, which shows the content immediately without extra loading.
This approach reduces the amount of JavaScript code sent to the browser, making pages load faster and improving user experience, especially on slow networks or devices.
Example
This example shows a simple server component in Next.js that fetches and displays the current date and time on the server.
import React from 'react'; // This is a server component because it uses async and fetches data export default function ServerTime() { const currentTime = new Date().toLocaleString(); return ( <div> <h1>Current Server Time</h1> <p>{currentTime}</p> </div> ); }
When to Use
Use server components when you want to:
- Fetch data securely on the server without exposing API keys or secrets to the browser.
- Render content that does not need client-side interactivity, like static text or lists.
- Improve page load speed by sending fully rendered HTML to the client.
- Reduce the amount of JavaScript sent to users, which helps on slow devices or networks.
For example, a blog post page that fetches content from a database can use server components to render the post on the server. Then, client components can be used only for interactive parts like comments or likes.
Key Points
- Server components run only on the server and never in the browser.
- They help improve performance by reducing JavaScript sent to the client.
- They can securely fetch data and access server resources.
- Use them for static or data-driven content without client interactivity.
- Combine with client components for interactive UI parts.