JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1360035
  • Score
    100M100P100Q184020F
  • License MIT

Integrate React Suspense into your apps

Package Exports

  • suspend-react

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (suspend-react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Build Size Version

npm install suspend-react

This library integrates your async ops into React suspense. Error-handling & loading states are handled at the parental level. The individual component functions similar to async/await in Javascript.

  • Chain your operations synchronously
  • No useEffect/setState hassle
  • No checking for the presence of your data
  • All React versions >= 16.6
import { Suspense } from 'react'
import { suspend } from 'suspend-react'

function Post({ id, version = 'v0' }) {
  const { by, title } = suspend(async (/*id, version*/) => {
    const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
    return await res.json()
  }, [id, version])
  return <div>{title} by {by}</div>
}

function App() {
  return (
    <Suspense fallback={<div>loading...</div>}>
      <Post id={1000} />
    </Suspense>
  )
}

What happened here?

  1. You have a promise, stick it into the suspend function. It will interupt the component.
  2. The component needs to be wrapped into <Suspense fallback={...}> which allows you to set a fallback.
  3. If suspend runs again with the same dependencies it will return the cached result.

Preloading

import { preload } from 'suspend-react'

async function fetchFromHN(id, version) {
  const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
  return await res.json()
}

preload(fetchFromHN, [1000, 'v0'])

Cache busting

import { clear } from 'suspend-react'

// Clear all cached entries
clear()
// Clear a specific entry
clear([1000, 'v0'])

Peeking into entries outside of suspense

import { peek } from 'suspend-react'

// This will either return the value (without suspense!) or undefined
peek([1000, 'v0'])

Typescript

Correct types will be inferred automatically.

React 18

Suspense, as is, has been a stable part of React since 16.6, but React will likely add some interesting caching and cache busting APIs that could allow you to define cache boundaries declaratively. Expect these to be work for suspend-react once they come out.

Demos

Fetching posts from hacker-news: codesandbox