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.
npm install suspend-reactVerified import paths — ran on the pinned version, not inferred.
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.
Use a robust key generation strategy (e.g., combining IDs, types, and versions) to ensure uniqueness. Consider the scope of your keys when multiple components might use similar data patterns.
Ensure your project uses React version 17.0 or higher to satisfy the peer dependency. Upgrade React if necessary: `npm install react@^17.0 react-dom@^17.0`.
Always wrap components that use `suspend` (or their parents) in an Error Boundary component to gracefully handle potential runtime errors from asynchronous operations. Example: `<ErrorBoundary><Suspense fallback={...}><MySuspendingComponent /></Suspense></ErrorBoundary>`.Wrap the suspending component (or a common ancestor) with `<React.Suspense fallback={<div>Loading...</div>}>` and ensure the `fallback` prop is provided with a valid React element.Install the package using your package manager: `npm install suspend-react` or `yarn add suspend-react`.
Ensure you are using a named import for `suspend`: `import { suspend } from 'suspend-react';`