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

rx-xtra.react-hooks

v0.0.1

Published

React Hooks for RxJS Interoperability

Downloads

4

Readme

Rx Xtra: React Hooks

These hooks RxJS and React play nice with each other, synchronizing Observables and Subscriptions with React's component and state lifecycles. If you've ever wanted to use a little helping of RxJS in your React, this is a good start.

rx-xtra.react-hooks is part of Rx Xtra, a collection of RxJS utilities.

Created by Joel Shinness LinkTreeGithubBuy me a coffee!

Usage

useSubscribe

Manages a subscription over the lifecycle of a hook or component, optionally responding to updating state as well.

function useMyHook(positions:Observable<number>){
  // Take series of positions and console.log the velocity and acceleration
  useSubscribe(() => positions.pipe(
    scan(([pos, vel, acc], newPos) => {
      const newVel = newPos - pos;
      const newAcc = newVel - vel;
      return [newPos, newVel, newAcc];
    }, [0, 0, 0]).
    ).subscribe(([pos, vel, acc]) => { 
      console.log('Current', pos, vel, acc) 
    }).add(() => { 
      console.log('Good place for any other teardown logic!');
    })
  );
}

There is also a "deps" array that defaults to []. If you pass in states or props as dependencies, and the dependencies change, the existing subscription will end and a new one will be created (kinda like switchMap).

useObserve<Deps extends any[]>

This takes any number of states or props and creates a "stateful" Observable from them. By "stateful" that means that, whenever this Observable gets a subscription, the first thing it emits is the current (or last) value.

function useMyHook(){
  const [name] = useState('Joel');
  const name$ = useObserve([name]);

  useSubscribe(() => {
    const subscription = new Subscription();
    // Subscribe to name$ immediately
    subscription.add(name$.subscribe(([name]) => {
      console.log('Name is', name)
    }));

    // Wait a bit, then subscribe to name$
    subscription.add(concat(
      timer(1000).pipe(
        ignoreElements(), 
        tap({
          subscribe(): { console.log('Starting to wait'); }
          finalize(): { console.log('Done waiting'); }
        })
      ),
      name$.pipe(
        tap({
          subscribe(): { console.log('Now listening to name$')}
        })
      )
    ).subscribe(([name]) => {
      console.log('Now, the name is', name)
    }));

    // Trigger a change eventually
    subscription.add(timer(2000).subscribe(() => { setName('Jeff'); }));

    return subscription;
  });

}

// OUTPUT:
// Name is Joel
// Starting to wait
// .... 1000 ms elapses
// Done waiting
// Now listening to name$
// Now, the name is Joel
// Name is Jeff
// Now, the name is Jeff

useObserveChanges

This is the "stateless" version of useObserve, which just means that it doesn't emit the current value immediately on subscription.

function useMyHook(){
  const [name, setName] = useState('Joel');
  const name$ = useObserveChanges([name]);

  useSubscribe(() => {
    const subscription = new Subscription();
    
    // Subscribe to name$ immediately
    subscription.add(name$.subscribe(([name]) => {
      console.log('Name is', name)
    }));

    // Wait a bit, then subscribe to name$
    subscription.add(concat(
      timer(1000).pipe(
        ignoreElements(), 
        tap({
          subscribe(): { console.log('Starting to wait'); }
          finalize(): { console.log('Done waiting'); }
        })
      ),
      name$.pipe(
        tap({
          subscribe(): { console.log('Now listening to name$')}
        })
      )
    ).subscribe(([name]) => {
      console.log('Now, the name is', name)
    }));

    // Trigger a change eventually
    subscription.add(timer(2000).subscribe(() => { setName('Jeff'); }));

    return subscription;
  });

}

// OUTPUT:
// Starting to wait
// .... 1000 ms elapses
// Done waiting
// Now listening to name$
// .... another 1000 ms elapses
// Name is Jeff
// Now, the name is Jeff

The only difference between this and useObserve is that "Now, the name is Joel" doesn't happen. This is perfect for using the change as a signal to trigger the start or end of some process.

useSubject

Subjects are the extension cords of RxJS. If you think of an Observer like a lamp, and an Observable like the wall socket, then Subjects can help you have the two connected, even if they're in different sides of the room.

useSubject has a simple job: it creates an instance of a Subject that will be created on mount, and completed on unmount. This uses a ref instead of a state, so it's the same object instance throughout the lifecycle of the component or hook, regardless of the re-renders.

useBehaviorSubject

BehaviorSubjects are exactly like Subjects, but they're intended to be "stateful", like Signals in Knockout, Solid, etc. They behave exactly like Subjects, except for three distinctions:

  • They're instantiated with an initial value
  • They have a .value data member that gives you the last emitted value (or the initial value if none has been emitted).
  • When you subscribe to a BehaviorSubject, it immediately emits that current value first.