Performance: Server component database queries
This affects the page load speed by controlling when and how data is fetched from the database during server rendering.
Jump into concepts and practice - no test required
import { fetchData } from '@/lib/db'; export default async function Page() { const data = await fetchData(); return <div>{data.title}</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.title}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side fetch in React useEffect | Adds extra DOM nodes for loading state | Triggers multiple reflows during loading and data update | Higher paint cost due to incremental updates | [X] Bad |
| Server component async data fetch | Minimal DOM nodes, fully rendered HTML | Single reflow on initial load | Lower paint cost with ready content | [OK] Good |
export default async function Users() {
const users = await db.query('SELECT id, name FROM users');
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}export default function Products() {
const products = await db.query('SELECT * FROM products');
return (
<div>{products.length} products found</div>
);
}export default async function UserPosts() {
const user = await db.query('SELECT * FROM users WHERE id = 1');
const posts = await db.query('SELECT * FROM posts WHERE userId = 1');
return (
<section>
<h1>{user.name}</h1>
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
</section>
);
}
What is the best way to optimize these queries?