Search⌘ K
AI Features

Client-Side Data Fetching with SWR

Explore client-side data fetching in Next.js with SWR to manage dynamic remote data. Understand how to use the useSWR hook for caching, automatic revalidation, and handling loading and error states to complement server-side rendering strategies.

We’ve covered the standard pattern for data fetching in Next.js: perform the work on the server. We learned to use async Server Components to fetch data for the initial render, and we saw how fetch caching, static generation (SSG), and revalidation (ISR) work together on the server to deliver fast, static HTML pages.

So, why would we need another way to fetch data?

The server-side methods are optimized for the initial page load. But for highly dynamic, interactive scenarios, fetching data directly from the browser is more efficient than rerendering an entire server component.

This is called client-side data fetching. It complements our server-side strategies by managing remote data that is requested and updated entirely within the browser.

Managing remote data with SWR

While we could use useState and useEffect to fetch data on the client, we’d quickly run into challenges:

  1. If we navigate away and come back, the component re-fetches the data, even if it hasn’t changed.

  2. A ...