http://localhost:3000
In React 19, form handling has become simpler and more powerful with built-in support for server actions and the new useActionState
hook. In this post, we'll build a modern, type-safe login form using useActionState
for form submission and Zod for server-side validation.
Prerequisites
Before we begin, we need to have some dependencies:
- Zod: for schema-based validation.
- Lucide Icons: for showing loading indicators.
Step 1: Setting Up the Form
We'll start by creating a simple login form, which includes email and password fields together with a submit button.
Step 2: Create the Server Action
Now, let's create a server action that will handle the form submission. This action will validate the inputs using Zod and return appropriate responses.
Step 3: Hook It All Together
Now, we can use the useActionState
hook to handle form submission and manage the form states. This hook will automatically handle the form submission, validation, and error states.
Let's break down the key parts of the above code:
- We use the
useActionState
hook to manage the form state and handle the action submission. - The
action
function is passed to theform
element, which allows it to handle the form submission. - The
isPending
state indicates whether the form is currently being submitted, allowing us to disable the form fields and button during submission and display the loading indicator. - We handle validation errors by checking the
state.errors
object and displaying error messages below the respective input fields. - The
data-error
attribute is used to apply styles conditionally based on whether there are validation errors.
Final Thoughts
With React 19's useActionState
and Zod, form handling becomes more intuitive, type-safe, and scalable. This server-first approach avoids onSubmit
boilerplate and makes your forms resilient, with proper validation and loading feedback out of the box.