Migrating from useState
useLocalActions is a drop-in replacement for one or many useState hooks in the same component. Same render-cycle semantics, same component-scoped lifetime, same React testing tools — the difference is how state changes are expressed.
The mapping in one screen
Section titled “The mapping in one screen”// Before — plain Reactfunction SignupForm() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [newsletter, setNewsletter] = useState(false); const [submitted, setSubmitted] = useState(false);
return ( <form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }} > <input value={name} onChange={(e) => setName(e.target.value)} /> <input value={email} onChange={(e) => setEmail(e.target.value)} /> <label> <input type="checkbox" checked={newsletter} onChange={(e) => setNewsletter(e.target.checked)} /> Subscribe </label> <button type="submit">Sign up</button> </form> );}// After — useLocalActionsimport { useLocalActions } from '@input-actions/core';
function SignupForm() { const { state, actions } = useLocalActions({ name: '', email: '', newsletter: false, submitted: false, });
return ( <form onSubmit={actions([ ['action/event', 'event/preventDefault'], ['action/save', ['submitted'], true], ])} > <input value={state.name} onChange={actions(['action/save', ['name'], 'event/target.value'])} /> <input value={state.email} onChange={actions(['action/save', ['email'], 'event/target.value'])} /> <label> <input type="checkbox" checked={state.newsletter} onChange={actions(['action/save', ['newsletter'], 'event/target.checked'])} /> Subscribe </label> <button type="submit">Sign up</button> </form> );}Same component lifecycle. Same form. No closures capturing event values; no (e) => set...(e.target.value) boilerplate per field.
Recipe
Section titled “Recipe”-
Group your
useStatecalls into one initial state object.// beforeconst [name, setName] = useState('');const [email, setEmail] = useState('');// afterconst { state, actions } = useLocalActions({ name: '', email: '' });If you had ten
useStatecalls, you now have oneuseLocalActionsand one state object. Read fields fromstate.x; write them viaactions(...). -
Replace setters with
actions(...)calls.The vast majority of
setX(value)becomesactions(['action/save', ['x'], value]). For event-derived values, use the placeholder:// before<input onChange={(e) => setName(e.target.value)} />// after<input onChange={actions(['action/save', ['name'], 'event/target.value'])} />For checkboxes,
'event/target.checked'; for selects,'event/target.value'; etc. See event placeholders for the full list. -
Replace counter / toggle patterns with their action types.
Before After setCount((c) => c + 1)actions(['action/increment', ['count']])setCount((c) => c - 1)actions(['action/decrement', ['count']])setOpen((o) => !o)actions(['action/toggle', ['open']])setItems((arr) => [...arr, x])actions(['action/push', ['items'], x])setItems((arr) => arr.filter(i => i !== x))actions(['action/remove', ['items'], x])setObj((o) => ({ ...o, k: v }))actions(['action/merge', ['obj'], { k: v }])setSomething(initial)(reset)actions(['action/reset'])oractions(['action/reset', ['something']])These map onto the sync state action types. No closure capturing the previous value — the executor reads it from current state at dispatch time, so the stale-closure problem disappears.
-
For multi-action handlers, pass an array.
// before — easy to forget preventDefault<form onSubmit={(e) => {e.preventDefault();setSubmitting(true);setError(null);}}>// after — every step is a tuple<form onSubmit={actions([['action/event', 'event/preventDefault'],['action/save', ['submitting'], true],['action/save', ['error'], null],])}> -
For state-derived payloads or conditional dispatch, fall back to a callback.
actions(...)covers the 90% case. When the payload requires logic at dispatch time, reach forexecuteActions(also returned from the hook):const { state, actions, executeActions } = useLocalActions({ tags: [], draft: '' });<inputonKeyPress={(e) => {if (e.key === 'Enter' && state.draft.trim()) {executeActions([['action/push', ['tags'], state.draft.trim()],['action/save', ['draft'], ''],], e);}}}/>This is the escape hatch. Use it sparingly; most handlers fit the tuple shape.
Common patterns
Section titled “Common patterns”Form fields
Section titled “Form fields”// beforeconst [form, setForm] = useState({ name: '', email: '' });<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>
// afterconst { state, actions } = useLocalActions({ form: { name: '', email: '' } });<input value={state.form.name} onChange={actions(['action/save', ['form', 'name'], 'event/target.value'])}/>The path array (['form', 'name']) descends into nested objects — no manual spreading. The library’s path utils handle the immutable update.
Lists with add / remove
Section titled “Lists with add / remove”// beforeconst [todos, setTodos] = useState([]);const addTodo = () => setTodos([...todos, { id: nextId(), text: draft }]);const removeTodo = (id) => setTodos((arr) => arr.filter((t) => t.id !== id));
// afterconst { state, actions } = useLocalActions({ todos: [] });// Add — push the new item directly<button onClick={actions([ ['action/push', ['todos'], { id: nextId(), text: 'Buy milk' }],])} />// Remove — pass the item; action/remove filters by strict equality.// For object lists, consider modelling as Record<id, Todo> instead and// dispatching `['action/save', ['todos', id], undefined]` to drop a slot.Counters and toggles
Section titled “Counters and toggles”// beforeconst [count, setCount] = useState(0);const [open, setOpen] = useState(false);
// afterconst { state, actions } = useLocalActions({ count: 0, open: false });<button onClick={actions(['action/increment', ['count']])}>+</button><button onClick={actions(['action/toggle', ['open']])}>Toggle</button>The increment/decrement actions take a path; the executor reads the current value and dispatches the update. No (c) => c + 1 closure, no stale-value bugs.
Async work
Section titled “Async work”// before — three booleans + an effectconst [isLoading, setIsLoading] = useState(false);const [error, setError] = useState(null);const [data, setData] = useState(null);
const submit = async (formData) => { setIsLoading(true); setError(null); try { const result = await api.submit(formData); setData(result); } catch (e) { setError(e.message); } finally { setIsLoading(false); }};
// after — one async handler, lifecycle in _asyncconst handlers = { submit: async (formData) => api.submit(formData) };const { state, actions, isLoading, hasError, getError, getData } = useLocalActions({ _async: {} }, handlers);
<button onClick={actions([ 'action/async-prevent', 'submit', 'submit', currentFormData,])}> Submit</button>
{isLoading('submit') && 'Submitting...'}{hasError('submit') && <Error>{getError('submit')}</Error>}The lifecycle (loading / success / error) lives in state._async.submit. The hook gives you typed accessors for each.
Pitfall fixes
Section titled “Pitfall fixes”| Plain-React pitfall | useLocalActions fix |
|---|---|
Stale closure (setCount(count + 1) in setTimeout) | actions(['action/increment', ['count']]) reads current value at dispatch time |
| Forgotten preventDefault | ['action/event', 'event/preventDefault'] as first action in the list |
Manual nested-object spread ({ ...obj, k: v }) | action/save with a path, or action/merge |
| Three booleans for async lifecycle | One async action, lifecycle in _async, accessors on the hook |
useEffect chains coordinating state | Action-level onSuccess / onError carry follow-up actions as data |
What you can still do with refs
Section titled “What you can still do with refs”useLocalActions only replaces useState. useRef still applies for:
- DOM references (e.g., focusing an input)
- Mutable values you read but never re-render on (timers, intervals, abort controllers)
- Imperative APIs (e.g., third-party libraries that expose handles)
The line stays the same: refs are escape hatches for things outside the render cycle. State that drives rendering goes through useLocalActions.
Where to go next
Section titled “Where to go next”- useReducer + Context migration — for state shared between components.
- Action types reference — full list of action variants and event placeholders.
- Global state quickstart — when you’re ready to lift state above one component.