Local state — useLocalActions
The simplest entry point. One hook holds your component’s state; actions(...) builds React event handlers from action tuples.
The whole thing
Section titled “The whole thing”import { useLocalActions, type AsyncHandlerContext } from '@input-actions/core';
type SignupData = { name: string; email: string; newsletter: boolean };
// Async handlers live outside the component. Each gets the action's// arguments, then `{ signal, getState }`.const handlers = { signUp: async ({ signal, getState }: AsyncHandlerContext<{ form: SignupData }>) => { const res = await fetch('/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(getState().form), signal, }); if (!res.ok) throw new Error(`Sign-up failed (${res.status})`); return res.json(); },};
const initialForm: SignupData = { name: '', email: '', newsletter: false };
export default function SignupForm() { const { state, actions, isLoading, hasError, getError, getAsyncOp } = useLocalActions( { form: initialForm }, handlers, ); const sending = isLoading('signup');
return ( <form onSubmit={actions([ ['action/event', 'event/preventDefault'], ['action/async', 'signup', 'signUp', { strategy: 'prevent', onSuccess: [['action/reset', ['form']]], }], ])} > <input required value={state.form.name} onChange={actions(['action/save', ['form', 'name'], 'event/target.value'])} /> <input type="email" required value={state.form.email} onChange={actions(['action/save', ['form', 'email'], 'event/target.value'])} /> <label> <input type="checkbox" checked={state.form.newsletter} onChange={actions(['action/toggle', ['form', 'newsletter']])} /> Subscribe to newsletter </label> <button type="submit" disabled={sending}> {sending ? 'Sending…' : 'Sign up'} </button> <button type="button" onClick={actions(['action/reset', ['form']])}>Reset</button>
{hasError('signup') && <p role="alert">{getError('signup')}</p>} {getAsyncOp('signup')?.status === 'success' && <p>Thanks, you're signed up.</p>} </form> );}That’s the entire program. No reducer, no setup, no provider.
What’s happening
Section titled “What’s happening”useLocalActions(initialState, asyncHandlers)holds component-scoped state. The state shape is whatever object you pass in. The second argument names the async handlers this component’s actions can run.stateis the current value, read at render time.actions(input)takes an action tuple (or array of tuples) and returns a React event handler. The handler dispatches through a small executor that knows how to interpret each tuple.dispatch(action)runs one action right away. Use it outside JSX, for example in an effect or a timer; in JSX,actions(...)is shorter.'event/target.value'is a placeholder. The executor resolves it from the React event at dispatch time — so the action tuple stays pure data, no closures capturing live DOM references.
Sending the form
Section titled “Sending the form”Submitting is two actions on the form’s onSubmit, so Enter in a field submits too, and the browser checks required and type="email" before either runs:
['action/event', 'event/preventDefault']stops the browser’s own page-reloading submit. ThepreventDefault()helper builds the same tuple.['action/async', 'signup', 'signUp', options]calls thesignUphandler.'signup'is the operation id: it names this request’s status and is whatstrategycounts against. The two are separate because one handler can run under several ids, such as asaveRowhandler run assave-row-1andsave-row-2so each row loads and aborts on its own. When there’s only one caller, using the same word for both is fine.
The handler reads what to send with getState(), which returns the state at the moment it’s called. That keeps the action free of data, so the same tuple works in a binding or a machine’s onEnter, where there’s no render-time state to put in it. Pass values in the action only when they’re chosen at the call site, such as an item id or 'event/arg'.
The executor tracks the request at state._async.signup: status goes 'loading', then 'success' or 'error', with the handler’s result at data or its thrown message at error. Read it with isLoading('signup'), hasError('signup'), getError('signup') and getAsyncOp('signup'), as the button and messages above do. There’s no submitting flag of your own to set and clear.
The options object controls the rest:
strategy: 'prevent'ignores further submits while one is in flight, so a double click sends once. Disabling the button is just the visible half of that.onSuccessruns actions after the handler resolves; here it clears the form.onErrordoes the same on failure. Resetting['form']rather than the whole state keeps_async.signup, so the success message stays.
Keep data you need later in your own state, not in _async: put it there from onSuccess, or return { successActions } from the handler when the actions need the response (see Async state as lifecycle metadata).
Multiple actions in one handler
Section titled “Multiple actions in one handler”Pass an array of tuples. The discriminator is the first element: a string means “one action,” a nested array means “list of actions.”
<button onClick={actions([ ['action/push', ['tags'], state.draft], ['action/save', ['draft'], ''], ])}> Add tag</button>When the actions depend on the event
Section titled “When the actions depend on the event”Sometimes which actions run depends on the event or on state: add a tag only when the key is Enter and the draft isn’t empty. Write that as a binding factory, a function that receives the call’s arguments and returns the actions to run:
import { defineBindings, useLocalActions } from '@input-actions/core';import type { KeyboardEvent } from 'react';
const bindings = defineBindings({ tags: { onKeyDown: (p: { draft: string }, e: KeyboardEvent) => e.key === 'Enter' && p.draft.trim() ? [ ['action/push', ['tags'], p.draft.trim()], ['action/save', ['draft'], ''], ] : [], },});
function TagInput() { const { state, actions, getBoundActions } = useLocalActions( { tags: [] as string[], draft: '' }, {}, [], bindings, ); const tags = getBoundActions('tags', { draft: state.draft });
return ( <input value={state.draft} onChange={actions(['action/save', ['draft'], 'event/target.value'])} onKeyDown={tags.onKeyDown} /> );}The factory’s first argument is the params you pass to getBoundActions, here the current draft; the event and any other call arguments follow. It returns plain tuples, so the logic sits outside JSX and is tested by calling it, and the same bindings record works with useBoundActions once the state moves to a store. Bindings are defined at module level, so render-time values reach them through params. The as string[] matters: TypeScript infers a bare [] as never[]. See the bindings quickstart for static bindings, typing and machine-rooted entries.
For work that waits on something, use an async handler and getState() as in Sending the form instead.
The escape hatch
Section titled “The escape hatch”executeActions (also returned from the hook) runs a list of actions immediately from any code, resolving placeholders from the event you pass. Use it when a binding doesn’t fit, such as a one-off in a third-party component’s callback:
onKeyDown={(e) => { if (e.key === 'Enter') executeActions([['action/save', ['draft'], '']], e);}}Tuples are the default, bindings handle event-dependent logic, and executeActions is the last resort.
- Global state quickstart — share state across components.
- Action bindings quickstart — hoist behaviour into a registry.
- Actions as data — the underlying idea.