jotai-statewatch
Lightweight, type-safe watcher and callback orchestration utilities for Jotai stores. Declaratively wire side-effects to atom state transitions — multi-atom fan-in conditions, debounced reactions, and gated intervals.
jotai-statewatch
Lightweight, type-safe watcher + callback orchestration utilities for Jotai stores. It helps you declaratively wire side-effects to atom state transitions without scattering ad-hoc useEffect logic across your app.
Features
- Deterministic watcher layer — wraps atoms and tracks current/previous values and change flags
- Multi-atom callbacks — react to combinations of atom changes in a single cohesive function
- Interval helpers — run gated periodic tasks only when conditions are met; auto-suspend when not
- Fan-in aggregators — consolidate multiple watcher events into a single typed event object
- Typed IDs and config maps — compile-time safety for watcher identifiers and callback wiring
- Explicit teardown — cleanly stop intervals, release resources, or unsubscribe
- No runtime dependency on React — works with Jotai store instances anywhere
Installation
npm install jotai-statewatch
Peer dependency: jotai ^2.4.0.
Quick Start
import { atom } from "jotai";
import {
defineWatchers,
defineWatcherCallback,
createWatcherManager,
} from "jotai-statewatch";
const countAtom = atom(0);
const thresholdAtom = atom(10);
const watcherMap = {
countWatcher: countAtom,
thresholdWatcher: thresholdAtom,
} as const;
const { create: createWatchers, WatcherIds } = defineWatchers(watcherMap);
const logWhenExceeded = defineWatcherCallback({
watchers: [WatcherIds.countWatcher, WatcherIds.thresholdWatcher] as const,
async callback(events) {
const { countWatcher, thresholdWatcher } = events;
if (!countWatcher.isChanged) return;
if (countWatcher.current > thresholdWatcher.current) {
console.log("Threshold exceeded!");
}
},
});
const runtimeWatchers = createWatchers();
const manager = createWatcherManager(runtimeWatchers, [logWhenExceeded]);
manager.start(store);
License
MIT © Goban Source, LLC.
Technologies Used
TypeScriptJotai