npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-subscribe-suspense

v0.0.1

Published

useSubscribe() hook with React Suspense support

Downloads

3

Readme

This package is built on the amazingly small but wonderful use-asset package. It allows you to suspend while your a subscription is loading, and gives you powerful controls over when to load, preload and unload your data.

:warning: Warning: this is experimental. While it's used in real world projects, there are no tests yet, and it currently only works on the client. If you like it, feel free to contribute!

useSubscribe with Suspense support

import React, { Suspense } from 'react'

function App() {
  return (
    <Suspense fallback={<b>Loading…</b>}>
      <Board id={123} />
    </Suspense>
  )
}

function Board({ id }) {
  useSubscription( 'board', id )
  // No need for ready checks; when you get here the subscription is ready
  return <div>Board {id}</div>
}

This is an example of basic usage; the useSubscription hook will initiate a subscription, which will suspend until it's ready. The subscription will automatically close when the component unmounts, and any errors in the publication will be thrown so they can be caught with an Error Boundary.

Using Suspense for this can make components lighter and easier to reason about, as you can read the code top down and assume the needed data is there without having to do ready() checks.

useSubscription hook

The code for this hook is fairly simple:

function useSubscription( name ...args ) {
  // This starts the subscription (if it is not preloaded yet)
  const { computation } = subscriptions.read( name, ...args )

  // This stops the subscription on unmount
  useEffect( () => () => {
    computation.stop()
  }, args )
}

This gives you a peak of how the use-asset API is used. This is exposed under a secondary export subscriptions, and this opens the door for some powerful stuff.

Powerful control over your subscriptions

As this package keeps a cache of subscriptions (needed for Suspense), we can do some fun stuff.

Keep subscription open after unmounting

There are cases where you wouldn't want to load data the user doesn't need, but after the user has requested it it's more efficient to just keep it in memory instead of stopping/restarting the subscription as the user navigates through the app. An example could be this All Projects list:

import { subscriptions } from 'rijk:react-subscribe-suspense'

function AllProjects() {
  subscriptions.read( 'projects.all' )
  const projects = useCursor( () => Projects.find({}), [] )
  return (
    <div>
      {projects.map( project => (
        <Project key={project.id} project={project} />
      ) )}
    </div>
  )
}

I used subscriptions.read instead of useSubscription here (the function signature is the same). This will suspend the component the first time it is called, but will not run the useEffect cleanup stopping the subscription. Therefore, the next time this component is mounted it will render immediately, without delay. This is similar to putting the subscription in a parent component, except that it's not initialized until the user requests the data the first time.

You can even choose the best strategy per subscription:

subscriptions.read( 'board', boardId ) // will be kept in memory
useSubscription( 'board.projects', boardId ) // will be stopped on unmount

Preloading data

Similar to .read(), there's also a .preload() method, that will silently initiate a subscription. This can be used to strategically preload data based on a user's actions:

<NavLink
  to={`/board/${board.id}`}
  onMouseEnter={() => {
    subscriptions.preload( 'board', board.id )
  }}
>
  {board.name}
</NavLink>

…or place in the app and likely next step:

function Welcome() {
  subscriptions.preload( 'dashboard' )
  
  return (
    <div>
      <p>Welcome back.</p>
      <NavLink to="/dashboard">Go to dashboard</NavLink>
    </div>
  )
}

You can also use this to initiate a subscription without suspending, more similar to useTracker(). This can be useful when the subscription doesn't contain essential data and you can already render some UI. You still keep the same powerful controls like preloading and choosing when to stop the subscription.