Performance: Why data fetching differs in Next.js
Data fetching methods in Next.js affect page load speed and interactivity by controlling when and how data is loaded and rendered.
Jump into concepts and practice - no test required
export async function getServerSideProps() { const res = await fetch('https://example.com/api/data'); const data = await res.json(); return { props: { data } }; } export default function Page({ data }) { return <div>{data.content}</div>; }
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.content}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side fetching in useEffect | Low (single root node) | Multiple reflows due to delayed content | High paint cost due to late content | [X] Bad |
| Server-side rendering with getServerSideProps | Low | Single reflow on initial load | Moderate paint cost, faster LCP | [!] OK |
| Static generation with getStaticProps + revalidate | Low | Single reflow on initial load | Low paint cost, fastest LCP | [OK] Good |
| Client-side fetching with SWR for user data | Low | No reflows blocking initial paint | Low paint cost, fast INP | [OK] Good |
getStaticProps to fetch data at build time for static generation.getServerSideProps is for server-side rendering, not build time; others are invalid function names.getServerSideProps to fetch data that changes every second?export async function getStaticProps() {
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return { data }
}props key containing the data, not just data alone.{ data } but should return { props: { data } } for Next.js to pass props correctly.