SWR — React Hooks library for data fetching

From the Next.js folks comes SWR, a React Hooks library for data fetching built on Suspense:

The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

It can avoid scenarios where you need to pass down a fetched user into several child components

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())

function useUser (id) {
  const { data, error } = useSWR(`/api/user/${id}`, fetcher)

  return {
    user: data,
    isLoading: !error && !data,
    isError: error
  }
}
// page component
function Page () {
  return <div>
    <Navbar />
    <Content />
  </div>
}

// child components
function Navbar () {
  return <div>
    ...
    <Avatar />
  </div>
}

function Content () {
  const { user, isLoading } = useUser()
  if (isLoading) return <Spinner />
  return <h1>Welcome back, {user.name}</h1>
}

function Avatar () {
  const { user, isLoading } = useUser()
  if (isLoading) return <Spinner />
  return <img src={user.avatar} alt={user.name} />
}

With SWR being used, this will result in only 1 request to /api/user/${id}.

The most beautiful thing is that there will be only 1 request sent to the API, because they use the same SWR key and the request is deduped, cached and shared automatically.

SWR — React Hooks library for data fetching →

React Suspense in Practice

Adam Rackis has written an extensive article on React Suspense for CSS-Tricks:

This post is about understanding how Suspense works, what it does, and seeing how it can integrate into a real web app. We’ll look at how to integrate routing and data loading with Suspense in React.

React Suspense in Practice →

📽 If you’re unfamiliar with Suspense, be sure to check out Dan Abramov introducing React Suspense first

React: Fetching data with lifecycle methods, hooks, or suspense — a comparison

Dmitri Pavlutin has compared the several ways to fecthing data in React.

Lifecycle methods had been for a long time the only solution to fetching. However fetching using them has problems with lots of boilerplate code, duplication, and reusability difficulties.

Fetching using hooks is a better alternative: way less boilerplate code.

Suspense’s benefit is declarative fetching. Your components are not cluttered with fetching implementation details. Suspense is closer to the declarative nature of React itself.

Bonus points for iterating on the hooks version by extracting it to a custom hook (which could be even further abstracted to a generic fetchData hook):

import React, { useState } from 'react';

import EmployeesList from "./EmployeesList";
import { fetchEmployees } from "./fake-fetch";

function useEmployeesFetch(query) {
  const [isFetching, setFetching] = useState(false);
  const [employees, setEmployees] = useState([]);

  useEffect(function fetch {
    (async function() {
      setFetching(true);
      setEmployees(await fetchEmployees(query));
      setFetching(false);
    })();
  }, [query]);

  return [isFetching, employees];
}

function EmployeesPage({ query }) {
  const [employees, isFetching] = useEmployeesFetch(query);
  
  if (isFetching) {
    return <div>Fetching employees....</div>;
  }
  return <EmployeesList employees={employees} />;
}

Lifecycle methods, hooks, suspense: which’s best for fetching in React? →