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

loxia

v1.0.1

Published

Implementing JavaScript state machines using React Hooks.

Downloads

5

Readme

loxia

Implementing JavaScript state machines using React Hooks.

Installation

npm install loxia

Motivation

I consider React Hooks to be particularly suitable for implementing state machines. Based on this idea, I developed a bookmark manager. It's UI makes intensive use of the Hooks and patterns developed here and serves as a real world test.

Hooks

In general, all Hooks in this library are built to be used with any React Hooks compliant implementation. That would be, for example, Batis, Preact, and of course React. In the usage examples, Batis is always used, but as an alternative, the analogous usage with React is shown as a comment.

useTransition

A transition is a function with special runtime behavior that can be used to implement the correct behavior of the transition methods of a state machine. A transition executes the passed callback once and returns true if its dependencies have not changed, so it should depend on the state of the associated state machine.

import {Host} from 'batis'; // import * as React from 'react';
import {createTransitionHook} from 'loxia';

const useTransition = createTransitionHook(Host /* React */);

function useLock(): Lock {
  const [locked, setLocked] = Host /* React */.useState(false);
  const transition = useTransition(locked);

  const lock = Host /* React */.useCallback(
    () => transition(() => setLocked(true)),
    [transition],
  );

  const unlock = Host /* React */.useCallback(
    () => transition(() => setLocked(false)),
    [transition],
  );

  return Host /* React */.useMemo(
    () => (locked ? {locked, unlock} : {locked, lock}),
    [locked],
  );
}
function createTransitionHook(hooks: BatisHooks): UseTransition;
type UseTransition = (
  ...dependencies: readonly [unknown, ...unknown[]]
) => Transition;
type Transition = (callback?: () => void) => boolean;

useBinder

A binding is a function that is tied to the life cycle of the Hook or component it surrounds. Often React components are already unmounted and an associated asynchronous operation should no longer have any effect. It is therefore useful to bind the callback functions of Promise.then, Promise.catch, and also setTimeout.

import {Host} from 'batis'; // import * as React from 'react';
import {createBinderHook} from 'loxia';

const useBinder = createBinderHook(Host /* React */);

function useExample() {
  const bind = useBinder();

  Host /* React */.useEffect(() => {
    setTimeout(
      bind(() => {
        // ...
      }),
    );
  });
}
function createBinderHook(hooks: BatisHooks): UseBinder;
type UseBinder = () => Bind;
type Bind = <TCallback extends (...args: any[]) => void>(
  callback: TCallback,
) => Binding<TCallback>;
type Binding<TCallback extends (...args: any[]) => void> = (
  ...args: Parameters<TCallback>
) => boolean;

useReceiver

A receiver is a state machine which allows the reception of a signal in the form of a promise passed as an argument. A receiver is always in one of the following states receiving, successful, or failed. As long as the reference to the passed promise remains the same, a receiver represents the state of the promise. When a reference to a new promise is passed, the old promise no longer affects the receiver state.

It makes sense to use a receiver if an asynchronous operation is based on user input. If the user input changes in the meantime and a new asynchronous operation overwrites the old one, the old one should no longer have any effect.

import {Host} from 'batis'; // import * as React from 'react';
import {createReceiverHook} from 'loxia';

const useReceiver = createReceiverHook(Host /* React */);

function useAsyncJsonData(url) {
  const signal = Host /* React */.useMemo(
    () => fetch(url).then((response) => response.json()),
    [url],
  );

  return useReceiver(signal);
}
function createReceiverHook(hooks: BatisHooks): UseReceiver;
type UseReceiver = <TValue>(signal: Promise<TValue>) => Receiver<TValue>;
type Receiver<TValue> =
  | ReceivingReceiver
  | SuccessfulReceiver<TValue>
  | FailedReceiver;

interface ReceivingReceiver {
  readonly state: 'receiving';
}

interface SuccessfulReceiver<TValue> {
  readonly state: 'successful';
  readonly value: TValue;
}

interface FailedReceiver {
  readonly state: 'failed';
  readonly error: unknown;
}

useSender

A sender is a state machine which allows to send exactly one signal at a time.

function createSenderHook(hooks: BatisHooks): UseSender;
type UseSender = () => Sender;
type Sender = IdleSender | SendingSender | FailedSender;

interface IdleSender {
  readonly state: 'idle';

  send(signal: Promise<unknown>): boolean;
}

interface SendingSender {
  readonly state: 'sending';
}

interface FailedSender {
  readonly state: 'failed';
  readonly error: unknown;

  send(signal: Promise<unknown>): boolean;
}