React Suspense Utilities

0.1.3 · active · verified Tue Apr 21

suspend-react is a utility library for integrating asynchronous operations seamlessly with React Suspense. It allows developers to define functions that return promises, which then 'suspend' rendering until the promise resolves, effectively bringing an `async/await` like paradigm to React components. The library manages pending and error states at a higher level via React's `<Suspense>` and Error Boundaries, reducing boilerplate in individual components. It features a global, key-based caching mechanism, similar to `useMemo` but with application-wide scope, supporting configurable cache invalidation via `lifespan` and custom equality functions. Additionally, it offers preloading, cache busting, and direct cache peeking utilities. The current stable version is 0.1.3, with recent patch releases in June 2023, indicating a stable yet actively maintained project under the pmndrs umbrella. It simplifies data fetching and resource loading within Suspense-enabled React applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `suspend` within a React component wrapped by `<Suspense>` to fetch and display data from an asynchronous source, handling loading states declaratively.

import { Suspense } from 'react';
import { suspend } from 'suspend-react';

function Post({ id, version }) {
  const data = suspend(async () => {
    // In a real app, use a more robust fetching mechanism and error handling
    const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`);
    if (!res.ok) {
      throw new Error(`Failed to fetch post ${id}: ${res.statusText}`);
    }
    return res.json();    
  }, [id, version]);

  return (
    <div>
      <h3>{data.title}</h3>
      <p>by {data.by}</p>
      <p>Score: {data.score}</p>
    </div>
  );
}

function App() {
  return (
    <Suspense fallback={<div>Loading post...</div>}>
      <h1>Hacker News Post</h1>
      <Post id={8863} version="v0" /> {/* A classic HN post ID */}
    </Suspense>
  );
}

// To run this in a simple environment, you might need a root component:
// import ReactDOM from 'react-dom/client';
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(<App />);

view raw JSON →