What is useActionState in React 19?
useActionState (formerly useFormState in preview builds) is a React 19 hook designed to dramatically simplify form submissions and Server Actions. It allows you to update component state based on the result of an asynchronous action, perfectly tying together the form's submission lifecycle.
How it works:
It takes an action function and an initial state, returning an array with:
- The current state: (e.g., error messages or success payloads from the server).
- A new action function: You pass this directly to the
<form action={...}>attribute. - A pending boolean: A flag indicating if the action is currently executing.
Why it's a game changer:
Historically, managing forms meant tracking isLoading, error, and success states manually with multiple useState calls and a complex onSubmit handler. useActionState handles the entire lifecycle for you natively, even automatically resetting the form upon a successful submission.
Code example
1import React, { useActionState } from 'react';23// Simulated Server Action4async function subscribeAction(previousState, formData) {5 const email = formData.get('email');67 // Simulate network latency8 await new Promise(r => setTimeout(r, 1500));910 if (!email.includes('@')) {11 return { success: false, message: 'Invalid email address.' };12 }1314 return { success: true, message: `Successfully subscribed ${email}!` };15}1617export default function NewsletterForm() {18 // Initializing useActionState19 // Returns: [currentState, boundAction, isPending]20 const [state, formAction, isPending] = useActionState(subscribeAction, null);2122 return (23 <div className="max-w-md mx-auto mt-10 p-6 bg-slate-50 border rounded-2xl shadow-sm">24 <h2 className="text-2xl font-bold mb-6">Join our Newsletter</h2>2526 {/* We pass the bound action directly to the form */}27 <form action={formAction} className="space-y-4">28 <input29 type="email"30 name="email"31 placeholder="Enter your email"32 required33 className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500"34 />3536 <button37 type="submit"38 disabled={isPending}39 className="w-full bg-blue-600 text-white font-bold py-3 rounded-lg disabled:bg-blue-300 disabled:cursor-not-allowed transition-colors"40 >41 {isPending ? 'Subscribing...' : 'Subscribe Now'}42 </button>43 </form>4445 {/* Status Messages rendered from the state */}46 {state && (47 <div className={`mt-4 p-4 rounded-lg ${state.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>48 {state.message}49 </div>50 )}51 </div>52 );53}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.