Skip to content

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.

// Before — plain React
function 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 — useLocalActions
import { 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.

  1. Group your useState calls into one initial state object.

    // before
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    // after
    const { state, actions } = useLocalActions({ name: '', email: '' });

    If you had ten useState calls, you now have one useLocalActions and one state object. Read fields from state.x; write them via actions(...).

  2. Replace setters with actions(...) calls.

    The vast majority of setX(value) becomes actions(['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.

  3. Replace counter / toggle patterns with their action types.

    BeforeAfter
    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']) or actions(['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.

  4. 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],
    ])}>
  5. 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 for executeActions (also returned from the hook):

    const { state, actions, executeActions } = useLocalActions({ tags: [], draft: '' });
    <input
    onKeyPress={(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.

// before
const [form, setForm] = useState({ name: '', email: '' });
<input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
// after
const { 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.

// before
const [todos, setTodos] = useState([]);
const addTodo = () => setTodos([...todos, { id: nextId(), text: draft }]);
const removeTodo = (id) =>
setTodos((arr) => arr.filter((t) => t.id !== id));
// after
const { 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.
// before
const [count, setCount] = useState(0);
const [open, setOpen] = useState(false);
// after
const { 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.

// before — three booleans + an effect
const [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 _async
const 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.

Plain-React pitfalluseLocalActions 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 lifecycleOne async action, lifecycle in _async, accessors on the hook
useEffect chains coordinating stateAction-level onSuccess / onError carry follow-up actions as data

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.