[]previous and next page

A hook written like useSignal

useSignal is a signal node, a reader and a writer:

For agentsUpdated

useSignal is a signal node, a reader and a writer:

src/use-toggle.tsts
import { type Accessor, createSignalNode, readSignal, writeSignal } from "@shadow-js/core/extend";

/** A boolean cell with a `toggle` action. Works at module scope and inside components. */
export function useToggle(initial = false, name?: string): [Accessor<boolean>, () => void] {
  const signal = createSignalNode<boolean>(initial, Object.is, name);
  const read: Accessor<boolean> = () => readSignal(signal);
  const toggle = (): void => {
    writeSignal(signal, !signal.value);
  };
  return [read, toggle];
}
  • createSignalNode(value, equals, name?) stores the value and the observers. equals is Object.is, your own (prev, next) => boolean, or false to notify on every write.
  • readSignal(node) returns the value and subscribes the running computation (nothing when none runs). node.value reads without subscribing, which is what you want inside the writer.
  • writeSignal(node, next) stores, and notifies only if equals says it changed. In development it throws WRITE_IN_MEMO (a ShadowError) when a memo is computing.

Nothing else is needed: scheduling, batching, ordering and glitch-free propagation are the engine's job.