Performance: Fetch in server components
Fetching data in server components affects the initial page load speed and server response time.
Jump into concepts and practice - no test required
export default async function Page() { const res = await fetch('https://example.com/api/data'); const data = await res.json(); return <div>{data.message}</div>; }
import React from 'react'; export default function Page() { const [data, setData] = React.useState(null); React.useEffect(() => { fetch('/api/data').then(res => res.json()).then(setData); }, []); if (!data) return <p>Loading...</p>; return <div>{data.message}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client fetch in useEffect | Low initially, then updates DOM | Multiple reflows due to loading state and data update | Higher paint cost due to delayed content | [X] Bad |
| Server fetch in server component | DOM fully rendered once | Single reflow on initial paint | Lower paint cost with immediate content | [OK] Good |
fetch() call to get data before rendering?await fetch() inside async server componentsawait fetch() directly inside an async server component fetches data before rendering.await fetch() -> Option Cawait fetch() [OK]await to wait for it to resolve.res.json() on the response to parse JSONres.json() to get the parsed data, also awaited or chained with then.export default async function Page() {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todo = await res.json();
return {JSON.stringify(todo)};
}{"userId":1,"id":1,"title":"delectus aut autem","completed":false} [OK]export default function Page() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return <div>{data.title}</div>;
}const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]) to fetch simultaneously.