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? →