0
0
NextjsConceptBeginner · 3 min read

What is Server Component in Next.js: Simple Explanation and Example

A 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.

javascript
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>
  );
}
Output
<h1>Current Server Time</h1> <p>6/10/2024, 3:45:12 PM</p>
🎯

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.

Key Takeaways

Server components render on the server and send ready HTML to the browser.
They improve performance by reducing client-side JavaScript.
Use them to securely fetch data and render static content.
Combine server and client components for best user experience.
Server components never run in the browser.