Skip to content
Andrea Lab

ANDREA LAB / BLOG

Forms with React Hook Form and Zod that preserve the user's work

How to separate form values, validation, and the API contract so a failed submission can be corrected without starting again.

Someone fills out a request to reserve a workspace. They add two guests, enter their details, and press Submit. The API returns a temporary error. If the screen resets, they have to repeat several minutes of work. If a message appears far from the field that needs attention, they may submit the same data again without understanding what is missing.

In React with TypeScript, React Hook Form can coordinate values, submission state, and repeatable fields. Zod defines validation rules that run against the supplied data. The workflow connects those pieces to server responses so each error leads to an understandable action.

Distinguish editing values from the submission contract

An empty text input is usually represented as an empty string during editing. The API may expect null for an optional value. Defining the transformation in one place keeps individual components from making different decisions.

For the example booking, an optional access reference can be sent as null when left empty. A guest name has another rule. Trim accidental whitespace at the edges and check that some text remains. Those decisions should respect the meaning of the field and the backend contract.

TypeScript types help during development. Zod checks values at runtime and supports schemas for objects and lists. Its documentation includes length rules and string transformations. Zod schemas.

Connect the schema to the form

The zodResolver adapter connects a schema to React Hook Form. This synthetic snippet defines a minimal booking with a guest list. Messages remain keys so a bilingual application can translate them.

import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const bookingSchema = z.object({
  contactName: z.string().trim().min(1, 'name_required'),
  guests: z.array(
    z.object({
      name: z.string().trim().min(1, 'guest_name_required'),
    }),
  ).min(1, 'guest_required'),
});

type BookingValues = z.infer<typeof bookingSchema>;

export function useBookingForm() {
  return useForm<BookingValues>({
    resolver: zodResolver(bookingSchema),
    defaultValues: {
      contactName: '',
      guests: [{ name: '' }],
    },
  });
}

The example focuses on structural rules. The server checks workspace availability and the caller's permissions when the request arrives. It may reject a well-formed booking if someone else reserved that time while the user was filling out the form.

Give repeatable rows an identity

To add or remove guests, useFieldArray manages the list within the form. Use the row identifier supplied by the hook as its React key. The position builds the registered field name, but changes when a row is removed.

In a list of three guests, removing the second should preserve the third guest's name and associated errors. Test that sequence with different data in every row. An empty list also requires an explicit product decision. It can be allowed or produce a message explaining how many people are required.

Put each response where it can be resolved

An availability error belongs to the booking as a whole. Data rejected by the server can point to a specific field. React Hook Form provides setError to associate errors with fields and supports global errors under root. The response adapter should recognize allowed field names and turn known codes into messages in the active language. React Hook Form errors.

After a failure, retain the values the person entered. For a general message, explain the next action, such as choosing another time or retrying the submission. If the server returns an unknown technical error, display a general response while keeping internal details out of the interface.

Decide what retrying means

Disabling the button while the request is pending helps prevent repeated clicks. If the connection drops after the server saved the booking, the person may submit again. The backend needs a policy for recognizing that retry and returning the outcome of the same operation where appropriate.

The interface can retain a stable submission identifier until the result is known. If the person edits the booking after a rejection, define when a new operation begins. That rule belongs to the contract between the screen and the API, alongside confirmation states.

Check the whole interaction

A relevant test fills in two guests, causes a server error, and verifies that both remain on screen. Another removes a middle row and checks that the remaining data retains its identity. Add an invalid-field case and an availability error to review focus behavior and message announcement.

For the booking, the practical outcome is that the person can correct or retry using the work they have already done. Schemas, repeatable fields, and API responses should sustain that continuity throughout submission.