A hook written like useSignal
useSignal is a signal node, a reader and a writer:
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.equalsisObject.is, your own(prev, next) => boolean, orfalseto notify on every write.readSignal(node)returns the value and subscribes the running computation (nothing when none runs).node.valuereads without subscribing, which is what you want inside the writer.writeSignal(node, next)stores, and notifies only ifequalssays it changed. In development it throwsWRITE_IN_MEMO(aShadowError) when a memo is computing.
Nothing else is needed: scheduling, batching, ordering and glitch-free propagation are the engine's job.