Rendering Data in Server Components
Свайпніть щоб показати меню
One of the biggest advantages of Next.js is that you can fetch and render data directly on the server.
In traditional React apps, data is often fetched in the browser using hooks like useEffect. In Next.js, Server Components allow you to fetch data before the page is sent to the user.
This means the user receives ready-to-render content immediately.
Fetching Data in a Server Component
Server Components can be asynchronous, which allows you to use await directly inside the component.
export default async function Page() {
const res = await fetch("https://api.example.com/products");
const products = await res.json();
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
How This Works
The data is fetched on the server before the page is rendered. The final HTML is then sent to the browser with the data already included.
The user does not need to wait for additional requests after the page loads.
Why This Is Better
Fetching data on the server improves performance and simplifies your code.
Instead of managing loading states and side effects in the browser, you can prepare everything on the server and send a complete page to the user.
This also improves SEO, because search engines receive fully rendered content.
Comparing with Client Fetching
In a client component, you would typically: | In a server component: |
|---|---|
Load the page first. | Data is fetched first. |
Fetch data after render. | The page is rendered with data. |
Update the UI when data arrives. | The user sees the final result immediately. |
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат