Validation errors that keep what the user typed
The first submit returns errors and the typed values; after the automatic reset the fields show those values again (they are the new defaultValues). The second submit succeeds and returns empty values, so the form clears.
const [state, formAction, isPending] = useActionState(fn, initialState) wraps an action so React keeps whatever it returned last as state, tells you while it runs, and queues calls one after another; it is the standard way to show a form's result and validation errors.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a like counter with useActionState whose action waits 200 ms and returns prev + 1, with a button that says Liking... while pending.
Write a newsletter action that returns { error: "Enter an email." } for an empty field and { message: "Thanks!" } otherwise, and render the result.
Explain it without notes
What does useActionState return, and what does the action receive?
How does useActionState handle several quick submissions?
Describe the validation errors pattern with useActionState.
What is the permalink argument for?
Preview
Console
Nothing logged yet.Expected console output
render pending=false errors= message=-
render pending=true errors= message=-
render pending=false errors=age,username message=-
username box after errors: asha
render pending=true errors=age,username message=-
render pending=false errors= message=Welcome, meera!