SWR 101 - React Hooks for Data Fetching

SWR is a fast, lightweight, and reusable data fetching package for React that uses the stale-while-revalidate caching strategy. By using this package, you can simplify and enhance your project’s data fetching logic.

Normally, data is fetched in a top level component using useEffect and passed down to its children using props. Additionally, logic must be added to handle errors and revalidation. This can lead to complicated and messy codebases, especially when data is needed throughout a large component tree. Enter, SWR.

npm install swr
import useSWR from 'swr';

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

function App() {
  return (
    <div>
      <Welcome />
      <Avatar />
    </div>
  );
}

function Welcome() {
  const { data, error } = useSWR('/api/user', fetcher);
  if (error) return <div>error</div>;
  if (!data) return <div>loading</div>;
  return <div>Welcome {data.name}!</div>;
}

function Avatar() {
  const { data, error } = useSWR('/api/user', fetcher);
  if (error) return <div>error</div>;
  if (!data) return <div>loading</div>;
  return <img src={data.avatar} alt={data.name} />;
}

In the example above, the useSWR(key, fetcher, options) hook returns data from cache (initially undefined), then sends a fetch request using fetcher (a custom fetch function that can use any library you want), and finally updates data and the cache from the response.

The amazing thing here is that data is independent of the component tree (parents don’t need to know anything or pass props) and because useSWR uses a key to fetch data, it avoids duplicate requests by sharing the cached data across all components (only 1 request is made). Not to mention that it handles errors and revalidation out of the box!

We can even make reusable hooks to make common fetch requests even easier to perform!

function useUser() {
  const { data, error } = useSWR(`/api/user/`, fetcher);
  return {
    user: data,
    isLoading: !error && !data,
    isError: error,
  };
}

SWR is a powerful package that simplifies and streamlines your data fetching logic. I’ve only touched on the core aspects of the package. For further reading, check out the links below.

Further Reading

Reply via email