MyInternships.in

Data Fetching & APIs

React SWR Data Fetching

SWR is a small data-fetching library built on the stale-while-revalidate idea: show cached data immediately, fetch fresh data in the background, then update the screen when it arrives.


What is SWR Data Fetching in React?

SWR is a small data-fetching library built on the stale-while-revalidate idea: show cached data immediately, fetch fresh data in the background, then update the screen when it arrives.

SWR Data Fetching example

A one-line fetch
JSX
import useSWR from 'swr';

const fetcher = url => fetch(url).then(r => r.json());

function Profile() {
  const { data, error, isLoading, mutate } = useSWR('/api/me', fetcher);

  if (isLoading) return <Skeleton />;
  if (error) return <p>Failed to load</p>;
  return <h1>{data.name}</h1>;
}

Key points to remember

  • Requests for the same key are deduplicated across components automatically.
  • It revalidates on window focus and on network reconnect by default.
  • mutate updates the cache locally for optimistic UI.
  • Passing null as the key skips the request — useful for dependent fetches.

SWR vs TanStack Query

SWRTanStack Query
Sizevery smalllarger
Devtoolsbasicexcellent
Mutationsmanual via mutatefirst-class useMutation
Best forsimple readscomplex caching and writes

React SWR Data Fetching— Interview Questions & FAQs

What does SWR stand for?+

Stale-while-revalidate — an HTTP caching strategy where the cached value is served immediately while a background request checks for a newer one.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships