Fetching and Rendering Data in Next.js
Deslize para mostrar o menu
In real applications, pages rarely display static content. Most of the time, you need to load data from an API and show it to the user.
In Next.js, this is done directly inside Server Components. You can fetch data and render it in the same place, without using additional hooks or complex logic.
This makes data handling simpler and more efficient.
Fetching Data
Server Components can be asynchronous, which allows you to use fetch with await:
export default async function Page() {
const res = await fetch("https://api.example.com/products");
const products = await res.json();
return <div>Data loaded</div>;
}
The data is fetched on the server before the page is rendered.
Rendering Data
Once the data is loaded, you can render it directly in your 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>
);
}
The user receives a fully rendered page with data already included.
How This Works
The server runs the component first, fetches the data, and generates the HTML. The browser then receives the final result.
This means there is no need to:
- Wait for data after page load;
- Manage loading state in simple cases;
- Write additional client-side logic for fetching.
Why This Approach Is Better
Fetching and rendering data on the server improves performance and simplifies your code.
The user sees content faster, and search engines can easily read the page because it is already fully rendered.
At the same time, your components stay clean because data fetching and rendering are handled in one place.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo