actions(...) and bindings factories
Natural spot for before-save normalization. The factory receives params; the tuple it returns is the normalized result. Trim, generate ids, branch on edge cases.
input-actions has one direction of data flow. Every piece is pure or near-pure. Knowing where in the pipeline to do a given piece of work — normalize an input, compute a total, format a string — is the most consequential design decision when you build with the library.
This page covers two things: the pipeline, and the rule for before-save vs after-save work.
Event → Action tuple → Executor → applyAction (reducer) → Store → Selector → UI ↑ ↓ bindings or actions(...) useStore(s => prepare...)setInterval callback, an async resolution.actions(['action/save', path, value]), via a registered binding (useBoundActions('id')), or programmatically (useDispatch(), store.dispatch(...)).'event/target.value' → the actual value), runs async strategies, validates machine transitions, dispatches follow-up actions.applyAction mutates state. The shared pure reducer (ADR 0015) computes the next state. Same function across every adapter.set, etc.), but consumers don’t see those internals.useStore((s) => prepareX(s)) runs against the new state. The result is what the component sees.Two surfaces where your code runs in this pipeline:
prepareUIData functions. The work happens between store and render.The library is designed to solve a specific cluster of problems documented in two articles (ADR 0020):
onError → parent → onErrorResolved between siblings — solved by both siblings reading the same store slice.useEffect synchronization. Effects watching state to mutate other state — solved by deriving downstream values from upstream ones via pure selectors.onSuccess / onError.The pipeline above is the answer to all six.
The interesting decision when you sit down to write a feature. The same logical operation could often go in either place; the answer depends on what kind of operation it is.
Use when you’re at a boundary — converting some external shape into the app’s domain shape, or capturing information that has no other source.
| Case | Why |
|---|---|
| Input normalization — trim whitespace, lowercase emails, strip formatting chars from card numbers | The “raw” form value isn’t worth keeping; the normalized form is what the app reasons about |
Generating ids / timestamps — id: Date.now() when pushing a new todo or message | The information isn’t in state — it comes from the wall clock or a randomness source |
Server response shaping — async handler maps {user_id, full_name} → {id, name} before dispatching action/save | The wire shape is incidental; the domain shape is what the rest of the app expects |
Composing a domain event from transient pieces — composer.send factory reads draft from params, builds { id, text: draft, done: false }, then clears draft | The action represents a transition; the store sees the result, not the keystrokes |
// Example: composing a domain event from transient piecesdefineBindings({ 'composer.send': { onClick: (p: { draft: string }) => { const id = String(Date.now()); // not in state — wall clock const trimmed = p.draft.trim(); // normalization if (!trimmed) return []; // skip dispatch if empty return [ ['action/push', ['todos'], { id, text: trimmed, done: false }], ['action/save', ['composer', 'draft'], ''], ]; }, },});// Example: server response shaping inside an async handlerasync fetchUser(userId, { signal }) { const raw = await api.get(`/users/${userId}`, { signal }); // Normalize wire shape → domain shape before the store sees it. store.dispatch(['action/save', ['users', raw.user_id], { id: String(raw.user_id), name: raw.full_name, email: raw.contact?.email ?? '', }]); return raw;}Use when you’re projecting domain data to a view shape, or computing a fact about state that’s a pure function of what’s already there.
| Case | Why |
|---|---|
Subtotals, totals, counts — prepareCart(state) derives line subtotals from price × qty | Storing them couples writes (every qty change has to update the total) |
Formatted display strings — formatMoney(cents), relative timestamps, full-name concatenation | Pure function of state; cheap; storing means stale data |
Validation flags / error messages — isAddressValid(state), prepareWizardGate(state) | The “is this valid?” answer is a function of the current values; storing it duplicates the source |
| Predicates that gate UI — disabled-button logic, “is the form dirty?”, row-highlight conditions | Selectors read narrow slices; React only re-renders when the derived value changes |
Filtering / sorting of lists — visibleTodos(state), sortedByPriority(state) | The full list is the model; views are arbitrary projections |
// Example: subtotals and totals derived from raw linesexport function prepareCart(state: AppState) { const lines = state.cart.lines.map((line) => { const item = state.catalog[line.itemId]; return { ...line, item, subtotalCents: item.price * line.qty, }; }); return { lines, subtotalCents: lines.reduce((sum, l) => sum + l.subtotalCents, 0), isEmpty: lines.length === 0, };}
function CartSummary() { const cart = useStore((s) => prepareCart(s), shallowEqualCart); return <p>{formatMoney(cart.subtotalCents)}</p>;}// Example: validation as derived stateexport function isAddressValid(state: AppState): boolean { const a = state.address; return !!(a.name.trim() && a.line1.trim() && a.city.trim() && a.postalCode.trim());}
function NextButton() { const canAdvance = useStore(isAddressValid); return <button disabled={!canAdvance}>Next →</button>;}State should be the canonical domain shape — the smallest representation that lets every other piece be derived. Anything that’s already implied by the store doesn’t belong in it; compute it on read.
Anything that isn’t implied by the store — fresh ids, wall-clock times, externally-shaped responses, user-input normalizations — normalize it before it lands, so the store stays clean.
Once you’ve committed to deriving after save, there’s a follow-up question: where in the consumer side does the prepare function actually execute? The default pattern is in the component, via a selector:
const cart = useStore((s) => prepareCart(s), shallowEqualCart);shallowEqualCart stands for any equality function that fits your shape. For the common case, a selector that returns a fresh object or array of values already in the store, use the built-in shallowEqual:
import { shallowEqual, useStore } from '@input-actions/core';
const { name, age } = useStore((s) => ({ name: s.user.name, age: s.user.age }), shallowEqual);It compares one level deep: arrays item by item, plain objects key by key, each with Object.is.
That works, but it’s worth understanding what it actually does, and the options when the default starts hurting.
useStore is useSyncExternalStoreWithSelector under the hood. When the store emits a change:
Object.is by default, your custom shallowEqualCart here).If 10 components subscribe with prepareCart, prepareCart runs 10 times per dispatch — once per subscriber. The library doesn’t share that work across subscribers. The equality check prevents the re-renders, not the recomputes.
For cheap pure functions (sub-millisecond), this is fine and matches React idiom. It starts to matter when the derivation is genuinely expensive, has many consumers, and the store mutates frequently.
The standard pattern, refined for ergonomics. The equality function lives with the prepare function instead of at every call site.
export function useCart() { return useStore((s: AppState) => prepareCart(s), shallowEqualCart);}function CartSummary() { const cart = useCart(); // no equality function to remember at the call site return <p>{formatMoney(cart.subtotalCents)}</p>;}Same performance characteristics as a direct useStore call, but the consumer code stays clean and the equality logic is in one place. This should be the default style — there’s no downside.
When the derivation is expensive and many components want the result, a tiny memoizer eliminates duplicate work across subscribers:
// src/memo.ts — five lines, zero dependenciesexport function memoLast<S, R>(fn: (s: S) => R): (s: S) => R { let last: { state: S; result: R } | undefined; return (state) => { if (last && last.state === state) return last.result; const result = fn(state); last = { state, result }; return result; };}import { memoLast } from './memo';
const memoizedPrepareCart = memoLast(prepareCart);
export function useCart() { return useStore((s: AppState) => memoizedPrepareCart(s), shallowEqualCart);}Now prepareCart runs once per state change — the other 9 subscribers hit the cache. The equality check still runs per-subscriber (to decide re-render), but the work that produces the candidate value is shared.
The cache key is state identity. Since applyAction returns a new state reference on every dispatch, this is essentially “cache the last state’s result.” For slice-level caching (recompute only when cart or catalog change, not on any mutation), reach for reselect — it’s a heavier dependency than memoLast, but the slice-input semantics are valuable when many derivations live downstream of stable slices.
prepareUIData(state)The maximalist form, from Christian Johansen’s article. One function returns the entire prop tree for the page:
export function prepareUIData(state: AppState) { return { cart: prepareCart(state), address: prepareAddress(state), payment: preparePayment(state), totals: prepareTotals(state), wizardGate: prepareWizardGate(state), };}Two ways to consume:
// (a) Narrow selector — prepareUIData runs once per subscriber per state change.const cart = useStore((s) => prepareUIData(s).cart, shallowEqualCart);
// (b) Memoize the top-level — prepareUIData runs once per state change, shared by all.const memoized = memoLast(prepareUIData);const cart = useStore((s) => memoized(s).cart, shallowEqualCart);When this shape wins:
prepareUIData(stateLiteral) returns the entire prop tree; assert against it.examples/date-form/ does this).When narrower selectors win:
Both compose. You can centralize prepareUIData for the page chrome and use narrow selectors for hot data lists.
If you’re already on Jotai, derived atoms cache across consumers for free:
const cartAtom = atom((get) => prepareCart(get(rootAtom)));// Components: useAtom(cartAtom) — re-runs only when rootAtom changes.Same idea is reachable via MobX computed on store.getBox(), or via thi.ng’s Cursor derivatives. These give you proper shared-result caching without rolling your own memoLast.
The trade-off: adapter lock-in. A component reading a derived Jotai atom won’t work on the SimpleStore, RTK, or Zustand adapters. If portability across adapters matters (it usually does for shared components), keep derivations in plain functions and reach for memoLast instead of adapter primitives.
| Situation | Strategy |
|---|---|
| Default for new code | Strategy 1 — custom hook wrapper |
| Profiling shows a derivation eating real time | Strategy 2 — wrap with memoLast |
| The page is state-chart-shaped, or you want one function to test | Strategy 3 — centralized prepareUIData (often combined with memoLast) |
| You’re locked into one adapter and want native caching | Strategy 4 — derived atoms / computeds / cursors |
| You’re tempted to store a derived value in state | Re-read Failure modes. Try Strategy 2 first. |
State should be the canonical domain shape — the smallest representation that lets every other piece be derived. If something is already implied by the store, don’t put it there; compute it on read.
If something isn’t implied by the store — fresh ids, wall-clock times, externally-shaped responses, user-input normalizations — normalize it before it lands, so the store stays clean.
Some state changes orthogonally to user intent — the wall clock advances, the window resizes, the user scrolls, the mouse moves, the network drops. The store is for what the user/app intends. This other category — what the environment is doing — needs a different home: a module-scope external subscribable that components observe with useSyncExternalStore.
| Category | Examples |
|---|---|
| Time | Wall clock, countdowns, “X ago” relative timestamps, one-shot expiry timers |
| Browser environment | Window size, scroll position, page visibility, online/offline, matchMedia breakpoints |
| Pointer & input ephemera | Mouse position, drag-in-progress, modifier keys held |
| DOM measurements | Element size (ResizeObserver), element visible (IntersectionObserver), focus state |
| Media playhead | Audio/video currentTime, animation frame counters |
The shared thread: high-frequency, observed by display elements only, never a domain fact. Putting any of it in the store would (a) flood DevTools, (b) make time-travel meaningless, (c) cause re-renders across every subscriber whether they cared or not.
// ❌ Don't do this. 1Hz dispatch for what's a pure display concern.useEffect(() => { const id = setInterval(() => { dispatch(['action/save', ['countdown', 'remainingMs'], expiresAt - Date.now()]); }, 1000); return () => clearInterval(id);}, [expiresAt]);Floods Redux DevTools with ticking entries; time-travel becomes meaningless; tests of state transitions get noisy; “store as model” gets violated.
Put a single stable fact in the application store (the timestamp expiresAt). Put the changing environment value (the wall clock) in a module-scope external store. Components subscribe to whichever they need — usually both, at the leaf where the value is displayed.
For time, @input-actions/timers ships exactly this. One shared 1Hz setInterval per page, lazy-started, lazy-stopped. Hooks (useClock, useCountdown, useTimeAgo, useExpiry) wrap the subscribable with selectors that narrow the re-render trigger to the derived value.
import { useStore } from '@input-actions/core';import { useCountdown, formatCountdown } from '@input-actions/timers';
function OfferBanner() { const expiresAt = useStore((s) => s.offer.expiresAt); const { remainingMs, isActive } = useCountdown(expiresAt); if (!isActive) return null; return <div>{formatCountdown(remainingMs)} remaining</div>;}The store holds the fact (expiresAt). The package’s clock holds the environment (Date.now()). The banner re-renders once a second because the formatted countdown changes; nothing else in the app re-renders.
For clearing the offer from state when time runs out, useExpiry is the one-shot companion — one setTimeout, dispatches a single action when reached:
import { useDispatch, useStore } from '@input-actions/core';import { useExpiry } from '@input-actions/timers';
function OfferExpiryWatch() { const expiresAt = useStore((s) => s.offer.expiresAt); const dispatch = useDispatch(); useExpiry(expiresAt, () => { dispatch(['action/save', ['offer', 'expiresAt'], null]); }); return null;}For the broader story — what makes the external-store pattern win over a custom useState + setInterval hook, the placement footgun, building your own subscribable for other categories, SSR / testing / lifecycle nuances — see the Orthogonal concerns page.
useLocalActions is still the answerExternal stores cover environment state. If you have transient component state with action-tuple discipline — a multi-field local form, a per-component validation flow, a local state machine — useLocalActions is the right tool.
| State shape | Tool |
|---|---|
| Environment (clock, scroll, online, mouse) | External store via useSyncExternalStore — e.g., @input-actions/timers |
| Component-local with action vocabulary | useLocalActions |
| Application-shared (the domain) | StoreProvider + useStore |
The RWA example uses @input-actions/timers end-to-end:
OfferBanner — useCountdown(expiresAt) for the 10-minute “Send Bonus” countdown.OfferExpiryWatch — useExpiry(expiresAt, () => dispatch(...)) for the one-shot cleanup.FeedScreen / TransactionDetail — every transaction row’s “X ago” string is useTimeAgo(tx.createdAt), so the feed self-updates as rows age past the minute boundary.All driven by the same shared 1Hz clock. Nothing in the application store moves until the user actually does something.
// Bad['action/save', ['cart', 'subtotalCents'], computeSubtotal(state)]Almost always premature. Selectors are cheap — useStore((s) => prepareCart(s), shallowEqualCart) only re-renders consumers when the derived value actually changes. Storing means manual sync on every write that affects the underlying lines. A single missed sync site is a stale-total bug.
If profiling later shows a derivation is genuinely expensive, memoize the selector (e.g., via reselect or a custom shallow-equality function), not the state.
// Bad['action/save', ['payment', 'cardNumber'], rawValue] // '4242 4242 4242 4242'Now every consumer has to normalize: the validation function, the display formatter, the submit handler. The normalize-on-read cost multiplies; subtle inconsistencies (one consumer trims, another doesn’t) creep in.
Normalize once at the boundary:
// Better['action/save', ['payment', 'cardNumber'], rawValue.replace(/\s/g, '')]// Bad — same shape conversion in five placesdispatch(['action/save', ['users', String(raw.user_id)], { id: String(raw.user_id), name: raw.full_name }]);// elsewhere: same code, same conversionIf the same boundary normalization shows up in multiple handlers, extract it once. The normalization is a domain function — normalizeUser(raw) — that all handlers call before dispatching. The action then stays trivial.
actions(...) and bindings factories
Natural spot for before-save normalization. The factory receives params; the tuple it returns is the normalized result. Trim, generate ids, branch on edge cases.
asyncHandlers
The boundary for server responses and other external sources. Shape there; dispatch the clean form.
useStore(s => prepareX(s))
Natural spot for after-save derivation. Pure selector + pure prepare function; component re-renders only when the derived value changes.
prepareUIData(state)
The maximalist version — one function returns the entire prop tree for a page. The date-form example uses this; see also Christian Johansen’s article.
The library makes both sides ergonomic. The discipline is yours: keep the store small and canonical; let selectors do the work between the model and the screen.
examples/checkout/ uses prepare.ts for all read-side derivations (prepareCart, prepareTotals, prepareWizardGate). The async handler in handlers.ts is where wire-shape → domain-shape happens for the order object.examples/date-form/ uses one centralized prepareUIData(state) — the maximalist form. Mirrors the Johansen article most closely.examples/chat/ normalizes incoming server messages in the sendMessage handler before pushing into messagesByChannel. Derives presence, search results, and outbox views in components via selectors.