useFormState for Server Responses
You'll learn how to capture and display server action return values—like success messages or validation errors—using the useFormState hook.
The Problem with Server Actions and User Feedback
When you submit a form that calls a server action, the action runs on the server and can return data. But how do you show that data to the user? If you just call the action, the return value disappears. You need a way to capture it and render it in your UI.
useFormState solves this by managing the server action's response as state.
How useFormState Works
useFormState wraps your server action and gives you two things:
- The current state (the last value returned by your server action)
- A wrapped action to use in your form's
actionprop
Here's the pattern:
'use client';
import { useFormState } from 'react-dom';
import { submitForm } from './actions';
export function MyForm() {
const [state, formAction] = useFormState(submitForm, null);
return (
<form action={formAction}>
<input name="email" type="email" />
<button>Submit</button>
{state?.error && <p style={{color: 'red'}}>{state.error}</p>}
{state?.success && <p style={{color: 'green'}}>Submitted!</p>}
</form>
);
}
Your server action must now accept the previous state as its first parameter:
'use server';
export async function submitForm(prevState, formData) {
const email = formData.get('email');
if (!email) return { error: 'Email required' };
// Process...
return { success: true };
}
Each time the form submits, the server action returns new state, and your component re-renders with that data.
Key Takeaway: useFormState connects server action return values to your UI state, letting you display validation errors, success messages, or any server response without manual state management.