React 19 is introducing some exciting new features, including a new compiler and support for form actions. One of the most interesting additions is the useFormState hook, which provides a powerful way to handle forms in your React applications. If you're using the Next.js App Router, you can start using these new tools right away!
To use form actions, you need two things: a form to post data to the action, and a server action that receives the form data, processes it, and returns a result. Let's start with the server side.
Creating a Server Action:
Create a new module, e.g., formPostAction.ts.
Define a server action function, e.g., onFormPostAction, as an async function.
Add the "use server" directive at the top of the file or as the first line of the function.
Define the shape of your form state using a type, e.g., FormState.
The server action function should take the previous state and form data as arguments and return the new state.
Using useFormState on the Client:
Import the useFormState hook from "react-dom".
Import the server action function from your server module.
Inside your component, call useFormState with the server action function and initial state.
useFormState returns a tuple containing the current state and an action function.
Pass the action function to the form's action property.
export default function MyForm() {
const [state, action] = useFormState(onFormPostAction, { message: "" });
const [first, setFirst] = useState("");
return (
<form action={action}>
<input
type="text" name="first"
value={first} onChange={(e) => setFirst(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
When the form is submitted, the data is sent to the server action, which processes it and returns the new state. You can display the returned state in your component by adding it to the JSX.
In summary, the useFormState hook in React 19 and Next.js App Router provides a streamlined and powerful way to handle forms in your applications. By creating server actions and using useFormState on the client, you can easily manage form state and submissions, while also benefiting from the added bonus of JavaScript-free form functionality.