Action Functions and State Updates
What you'll learn: How to write action functions that receive previous state and form data, then return new state when they complete.
The Core Pattern
With useActionState, your action function receives two arguments automatically:
- Previous state – the current state value before this action runs
- Form data – the
FormDataobject from the form submission
Your action function should return the new state you want after the action completes. React will update the state with whatever you return.
async function myAction(previousState, formData) {
const name = formData.get('name');
// Do async work (API call, etc.)
const result = await saveToServer(name);
// Return the NEW state
return {
...previousState,
success: true,
message: result.message
};
}
const [state, action] = useActionState(myAction, { success: false, message: '' });
Why This Matters
This pattern gives you automatic state management for async form actions. You don't need separate useState for loading/error states or manual try/catch blocks everywhere. The action function becomes your single source of truth for what happens when the form submits.
The previous state parameter lets you preserve existing data while adding new fields, or conditionally update based on what was there before.
Common Pattern
async function submitAction(prevState, formData) {
try {
const data = await api.submit(formData.get('input'));
return { status: 'success', data, error: null };
} catch (error) {
return { status: 'error', data: null, error: error.message };
}
}
Key Takeaway: Action functions receive previous state and form data, then return the new state object—React handles the rest of the update cycle automatically.