Time
Wall clock, countdowns, “X ago” relative timestamps, one-shot expiry timers.
The Data flow page introduced the distinction between state the store should hold (what the user/app intends) and state observed via external subscribables (what the environment is doing). This page goes deeper on the second category — what it includes, the specific challenges each one raises, and the patterns that handle them well.
The library ships one such subscribable today, @input-actions/timers. The other categories are sketches you’ll mostly build yourself; the patterns generalize cleanly.
State is orthogonal to the user’s intent when it changes without the user causing it. The clock advances whether the user clicks or not. The window resizes when someone drags the corner. The browser goes offline when a router dies. The mouse pointer moves between actions, not as part of them.
These are real, observable facts your UI needs to display — but they aren’t intentions and they don’t belong in a store of intentions.
Time
Wall clock, countdowns, “X ago” relative timestamps, one-shot expiry timers.
Browser environment
Window size, scroll position, page visibility, online/offline, matchMedia breakpoints, dark-mode preference.
Pointer & input ephemera
Mouse position, hover state, drag-in-progress, modifier keys held, current text selection.
DOM measurements
Element size (ResizeObserver), element visible (IntersectionObserver), focus state, clientHeight after layout.
Media playhead
Audio/video currentTime, animation frame counters, video buffered ranges.
Random / generated
Wall-clock-derived IDs, Math.random() values, crypto-generated keys — values that can’t be stored because they’re freshly minted on demand.
The common thread: each one changes at a frequency unrelated to user actions, and is observed by display elements only. None of them have “the user wanted X” semantics. None of them benefit from time-travel debugging.
Putting orthogonal state in the store breaks several disciplines at once:
Date.now() already knows the time. Mirroring those values into the store creates two sources to keep in sync — exactly the failure mode the store was meant to avoid.Every orthogonal concern fits the useSyncExternalStore contract:
function subscribe(listener: () => void): () => void;function getSnapshot(): T;A module-scope subscribable owns the value and notifies registered listeners when it changes. Components consume via useSyncExternalStore, which guarantees correct concurrent-mode behaviour and lets selectors narrow the re-render trigger.
// The template — pattern this for any orthogonal concern.import { useSyncExternalStore } from 'react';
const listeners = new Set<() => void>();let value: T = computeInitial();let started = false;
function start() { if (started) return; started = true; // Attach the underlying source — addEventListener, setInterval, // ResizeObserver, matchMedia listener, etc. source.attach((next: T) => { if (Object.is(next, value)) return; value = next; for (const fn of listeners) fn(); });}
function stop() { if (!started) return; started = false; source.detach();}
export function subscribe(listener: () => void): () => void { listeners.add(listener); if (listeners.size === 1) start(); return () => { listeners.delete(listener); if (listeners.size === 0) stop(); };}
export function getSnapshot(): T { return value;}
export function useThing(): T { return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);}The shape is the same whether you’re tracking time, window size, network status, mouse position, or an element’s bounding box. What changes is what fills in source.attach and source.detach.
The pattern above looks simple. The trickiness comes from edge cases — each one is worth knowing about up front.
If start() runs at module load instead of on first subscriber, you pay the cost (an open interval, an attached ResizeObserver, a registered event listener) for the entire session whether anyone’s listening or not. If stop() doesn’t fire when the last subscriber leaves, you leak resources across HMR reloads and test runs.
The fix is what the template shows — start on the first listeners.add, stop on the last listeners.delete. Worth a unit test that asserts vi.getTimerCount() returns to baseline after unmount.
useSyncExternalStore does Object.is-based equality between consecutive snapshots. If getSnapshot() returns a fresh object every call, every consumer re-renders on every tick.
// ❌ Bad — new object every call.function getSnapshot() { return { x: mouseX, y: mouseY };}
// ✅ Better — return a stable reference, mutated in place under the hood.let snapshot = { x: 0, y: 0 };function update(x: number, y: number) { if (x === snapshot.x && y === snapshot.y) return; snapshot = { x, y }; // new ref only when value changed for (const fn of listeners) fn();}function getSnapshot() { return snapshot; }Or — often simpler — return a primitive and let consumers compose:
function useMouseX() { return useSyncExternalStore(subscribe, () => snapshot.x); }function useMouseY() { return useSyncExternalStore(subscribe, () => snapshot.y); }Now useMouseX only re-renders when X changes; useMouseY only when Y changes.
The big win over useState + setInterval is that the snapshot can be derived instead of raw. useTimeAgo returns the formatted string '5m ago' rather than the raw clock value. 30 components subscribing all read the same string for 60 seconds straight — none of them re-render until the minute crosses.
The shape is just:
function useTimeAgoFor(timestamp: number): string { return useSyncExternalStore( subscribe, () => format(timestamp, getSnapshot()), () => format(timestamp, getSnapshot()), );}Apply the same idea anywhere: useScrollAtBottom() returns a boolean derived from scroll position, useViewportClass() returns a string 'mobile' | 'tablet' | 'desktop' from window width, etc.
useSyncExternalStore accepts a third argument, getServerSnapshot, for server rendering. Most orthogonal sources don’t exist on the server (no window, no Date.now() consistency, no navigator.onLine). The right pattern is a sensible “neutral” default:
function useOnline(): boolean { return useSyncExternalStore( subscribe, () => navigator.onLine, () => true, // SSR assumes online );}If client and server values diverge, you’ll see hydration warnings. The cure is either (a) render a neutral first paint and let the client re-render with the real value, or (b) gate the consumer behind a useIsClient() hook so it only renders after hydration.
Module-scope state survives across tests unless reset. Singleton subscribables need a __resetForTest() escape hatch:
export function __resetForTest(): void { stop(); listeners.clear(); value = computeInitial();}Run it in afterEach. Without this, the second test inherits the first test’s listeners, fake timers cross-pollinate, etc.
Vitest’s vi.useFakeTimers() works correctly with setInterval/setTimeout-based subscribables — vi.advanceTimersByTime(1000) fires them deterministically. For event-driven subscribables (window.addEventListener), you typically dispatch the event directly: window.dispatchEvent(new Event('online')).
Mouse position fires at the browser’s input rate (hundreds of Hz). Scroll fires per pixel. Naively notifying listeners every event = death by re-renders. Two common shapes:
RAF coalescing — collect events between frames, fire once per frame:
let pending = false;function onMove(e: MouseEvent) { rawX = e.clientX; rawY = e.clientY; if (!pending) { pending = true; requestAnimationFrame(() => { pending = false; if (rawX === snapshot.x && rawY === snapshot.y) return; snapshot = { x: rawX, y: rawY }; for (const fn of listeners) fn(); }); }}Fixed-interval polling — sample at a known cadence instead of every event:
setInterval(() => { if (scrollX === snapshot.scrollX) return; snapshot = { scrollX }; for (const fn of listeners) fn();}, 100); // 10Hz scroll updatesWhich to pick depends on the use case. RAF stays smooth visually; fixed-interval keeps update cost predictable.
Sometimes environment state needs to influence domain state — “auto-save when the user goes offline,” “pause the video when the page hides.” The bridge is a small headless component with useEffect:
function OfflineQueueOpener() { const isOnline = useOnline(); const dispatch = useDispatch(); useEffect(() => { if (!isOnline) { dispatch(['action/save', ['ui', 'queueOpen'], true]); } }, [isOnline, dispatch]); return null;}The orthogonal concern stays in its own subscribable; the bridge component reads it and dispatches an action when the right thing happens. This is the same pattern as OfferExpiryWatch in the RWA — a leaf component that owns one subscription and one dispatch path.
Module-scope state is per-tab. If you need a value synchronized across tabs (e.g., logged-in user across all open tabs of your app), you need a different shape — BroadcastChannel, storage events, or a service worker. These can be wrapped in the same useSyncExternalStore contract; the difference is what’s behind subscribe.
@input-actions/core’s store doesn’t help here directly — it’s per-page. Cross-tab coordination is itself an orthogonal concern with its own implementation patterns.
A short list of gotchas you’ll hit in practice:
navigator.onLine is unreliable — true doesn’t always mean reachable. Some apps prefer “no successful request in N seconds” as a stricter test.window.innerWidth doesn’t include the scrollbar; document.documentElement.clientWidth excludes it.ResizeObserver callbacks fire asynchronously and can cause infinite-loop warnings if the callback itself triggers a resize. Wrap mutations in RAF.matchMedia has subtle differences between mobile and desktop; the change event is generally reliable but addListener/removeListener are deprecated in favor of addEventListener.These don’t make the pattern wrong; they’re just the kind of platform detail that lives inside the subscribable’s implementation.
@input-actions/timers coversThe library ships time-based primitives because they’re load-bearing for so many UIs and because the pattern is cleaner to demonstrate than describe.
import { useClock, // current Date.now(); ticks every second useCountdown, // derived view from a target timestamp useExpiry, // one-shot setTimeout that fires a callback at a target useTimeAgo, // live "5m ago" string; only re-renders on boundaries formatCountdown, // duration → "M:SS" timeAgo, // pure formatter for relative time subscribe, // useSyncExternalStore contract — for building your own getSnapshot,} from '@input-actions/timers';A single shared 1Hz setInterval per page lifetime, lazy-started, lazy-stopped. Selector-narrowed hooks (useTimeAgo, useCountdown) so consumers re-render only when their derived value changes. The package is published independently of @input-actions/core because the principle — and the package — is useful in any React app.
The same shape, different start/stop. A few sketches:
const listeners = new Set<() => void>();let isOnline = typeof navigator !== 'undefined' ? navigator.onLine : true;
function update() { const next = navigator.onLine; if (next === isOnline) return; isOnline = next; for (const fn of listeners) fn();}
function start() { window.addEventListener('online', update); window.addEventListener('offline', update);}function stop() { window.removeEventListener('online', update); window.removeEventListener('offline', update);}
export function subscribe(listener: () => void) { listeners.add(listener); if (listeners.size === 1) start(); return () => { listeners.delete(listener); if (listeners.size === 0) stop(); };}
export const getSnapshot = () => isOnline;
export function useOnline() { return useSyncExternalStore(subscribe, getSnapshot, () => true);}function makeBreakpoint(query: string) { const mql = typeof window !== 'undefined' ? window.matchMedia(query) : null; const listeners = new Set<() => void>(); let matches = mql?.matches ?? false;
function update(e: MediaQueryListEvent) { if (e.matches === matches) return; matches = e.matches; for (const fn of listeners) fn(); }
return { subscribe(listener: () => void) { listeners.add(listener); if (listeners.size === 1) mql?.addEventListener('change', update); return () => { listeners.delete(listener); if (listeners.size === 0) mql?.removeEventListener('change', update); }; }, getSnapshot: () => matches, };}
const prefersDark = makeBreakpoint('(prefers-color-scheme: dark)');
export function usePrefersDark(): boolean { return useSyncExternalStore( prefersDark.subscribe, prefersDark.getSnapshot, () => false, );}ResizeObserverA per-element subscribable looks slightly different because each element has its own ResizeObserver entry. The hook holds a ref to the observed element and registers it on mount:
export function useElementSize() { const ref = useRef<HTMLElement | null>(null); const [size, setSize] = useState<{ w: number; h: number }>({ w: 0, h: 0 });
useEffect(() => { if (!ref.current) return; const obs = new ResizeObserver((entries) => { const { width, height } = entries[0].contentRect; setSize((prev) => (prev.w === width && prev.h === height ? prev : { w: width, h: height })); }); obs.observe(ref.current); return () => obs.disconnect(); }, []);
return [ref, size] as const;}This is the one shape where useState is the right primitive — the “store” is per-element, not module-scope, and there’s exactly one consumer (the element’s owner). The decision matrix:
useState + appropriate observer in useEffectThe pattern is the same idea (subscribe → notify → snapshot); the storage location changes.
useState is still rightExternal stores are the pattern when multiple components might consume the same value or when the source is module-scope-natural (the clock, the network, the window). For per-component transient state — a hover boolean on a specific row, a draft string in a single form — useState (or useLocalActions if you want the action-tuple discipline) is still the right primitive. The orthogonal-concern pattern is about shared environment state, not about every transient value.
The decision matrix:
| State shape | Tool |
|---|---|
| Shared environment (clock, network, viewport, media query, …) | Module-scope external store + useSyncExternalStore |
Per-element environment (ResizeObserver, IntersectionObserver, focus) | useState + observer in useEffect, returned via a ref |
| Per-component transient with action vocabulary | useLocalActions |
| Per-component transient, trivial shape | useState |
| Application-shared domain state | <StoreProvider> + useStore |
The library’s design splits state by whose intent it represents:
Application state (user/app intends) ↑ StoreProvider │ ┌───────────────┼───────────────┐ │ │ │ Local actions useStore / Adapters (component) useActions (RTK, Zustand, …) │ ↓ useLocalActions
Component state (transient, unintentful) ↑ useState
Environment state (orthogonal, observed) ↑ Module-scope subscribable + useSyncExternalStore │ ┌───────────────┴───────────────┐ │ │@input-actions/timers your own (online,(clock, countdown, viewport, matchMedia,expiry, time-ago) mouse, scroll, …)Three sources of state, each with its own subscription mechanism. They compose through:
createTransaction reading state.offer.expiresAt > Date.now()).OfferExpiryWatch reading expiresAt and dispatching on expiry).The discipline is to keep each kind of state in the source of truth that matches what it represents — and to compose explicitly at the boundaries.
@input-actions/timers package — the in-library example of this pattern.OfferBanner (selector-narrowed display), OfferExpiryWatch (one-shot dispatch bridge), and per-row useTimeAgo (shared-clock leaves).