Sub topic 12
Repeating fields with useFieldArray
This chapter assumes you can build a basic form with useForm, register, and handleSubmit, and that you can read a Zod object schema connected through zodResolver. You should also be comfortable with React keys and TypeScript generics.
Why a list of inputs needs its own hook
Some forms have a variable number of rows: invoice line items, phone numbers, tags, team members. A fixed set of register("name") calls cannot describe them, because the number of inputs changes while the user types.
You could keep the rows in useState and render them yourself. That breaks down quickly. You would have to keep React state, the registered input values, and the validation errors in step with each other whenever a row is added, removed, or moved.
useFieldArray solves this. It manages the list of rows inside the form's own state, and it gives you functions to change that list. The form then stays the single source of truth for values and errors.
The working model
useFieldArray takes two options: control (from useForm) and name (the path of the array in your form values). It returns fields and a set of methods.
fieldsis the array to render. Each entry holds the row's values plus a generatedid.append,prepend,insert,remove,swap,move,update, andreplacechange the array.
Each input in a row is still registered with register, using an indexed path such as items.0.name. The array hook handles the structure, and register handles each input.
The generated id is the reason the hook exists in this form. React needs a stable key for each row. If you use the array index as the key, removing the first row makes React reuse its DOM node for the next row, and inputs can show the wrong value. The id follows the row as it moves. Always use field.id as the key.
The generated id is stored under the key id in each entry of fields. If your own row data has a field named id, it is overwritten in fields. Use keyName only on older versions that support it, or avoid naming your own field id.
A complete example
The schema describes the array. The error for "no rows" belongs to the array itself, and the error for an empty name belongs to a single row.
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const listSchema = z.object({
items: z
.array(z.object({ name: z.string().min(1, "Name is required") }))
.min(1, "Add at least one item"),
});
type ListValues = z.infer<typeof listSchema>;
export function ItemsForm() {
const {
control,
register,
handleSubmit,
formState: { errors },
} = useForm<ListValues>({
resolver: zodResolver(listSchema),
defaultValues: { items: [{ name: "" }] },
});
const { fields, append, remove } = useFieldArray({ control, name: "items" });
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`items.${index}.name`)} />
{errors.items?.[index]?.name && (
<p role="alert">{errors.items[index]?.name?.message}</p>
)}
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={() => append({ name: "" })}>
Add item
</button>
<button type="submit">Save</button>
</form>
);
}Four details in this code matter.
defaultValuescontains the starting array. Without it,fieldsstarts empty and the form begins with no rows.- The key is
field.id, notindex. - The path `
items.${index}.nameis a template literal. TypeScript checks it againstListValues`, so a typo is a compile error. - Buttons that are not meant to submit have
type="button". A button inside a form defaults totype="submit", so a missing type makes "Add item" submit the form.
How the pieces connect
The diagram shows the flow of one change, from a click to a validated submission.
Reading errors for arrays
The shape of errors mirrors the shape of the data, with one complication. An array can have two kinds of error.
- A row error, such as an empty name, is at
errors.items?.[index]?.name. - An array-level error, such as "Add at least one item", is at
errors.items?.rootin current versions of React Hook Form. In older versions it is aterrors.items?.message.
Because errors.items can be either a list of row errors or a single error object, TypeScript makes you use optional chaining. Show the array-level message once, outside the map:
{errors.items?.root && <p role="alert">{errors.items.root.message}</p>}If the message does not appear, check your installed version and log errors.items to see where the message is.
Choosing the right method
Most forms need only append and remove. The other methods cover specific needs.
| Method | What it does | Typical use |
|---|---|---|
| `append(value)` | Adds a row at the end | "Add item" button |
| `prepend(value)` | Adds a row at the start | Newest first lists |
| `insert(index, value)` | Adds a row at a position | "Add row below" |
| `remove(index)` | Removes one row, or all rows if called with no argument | Delete button |
| `swap(a, b)` | Exchanges two rows | Up and down arrows |
| `move(from, to)` | Moves one row | Drag and drop |
| `update(index, value)` | Replaces one row | Editing from a dialog |
| `replace(values)` | Replaces the whole array | Loading data from an API |
Edge cases and common errors
Rows keep stale values after removal. This almost always means the key is index. Switch to field.id.
Typing in a row loses focus. This happens when the component that renders the row is defined inside the parent component. React sees a new component type on every render and remounts it. Define row components at module level.
append adds an empty object and validation fails on submit. Pass a complete row, such as append({ name: "" }). Passing nothing creates a row with undefined values. Every field in a row should have a defined starting value so the inputs stay controlled by the form consistently.
Primitive arrays do not work. useFieldArray does not support arrays of plain strings, such as tags: string[]. Wrap each value in an object, for example tags: { value: string }[], and convert back to strings before sending the data.
Default values for a row set after the first render. If you load existing rows from an API, pass them through reset or replace. Changing the defaultValues object after mount has no effect on its own.
Mixing fields with live values. fields reflects the structure and the values at the time of the last array operation. It does not update on each keystroke. If you need the current values, use watch or useWatch, which is covered in the performance chapter.
Focus after adding a row
append accepts a second argument for focus. By default the new row's first input receives focus, which helps keyboard users. You can choose another input with shouldFocus and focusName.
append({ name: "" }, { shouldFocus: true });Set shouldFocus: false if you add several rows in a loop, so focus does not jump for each one.
Summary of the rules
- Pass
controlandnametouseFieldArray, and givedefaultValuesa full starting array. - Render from
fields, key byfield.id, and register each input with an indexed path. - Describe the array with
z.array(...), and put row rules in the inner object and list rules on the array. - Use object rows, not plain strings.
- Mark every non-submit button with
type="button".
Exercise
A user removes the first of three rows, but the remaining rows show the wrong text in their inputs. The code uses key={index}. What causes this, and how do you fix it?
Show answer
With key={index}, React matches rows to DOM nodes by position, so after the first row is removed the second row's data is placed into the node that held the first row's input state. The fix is to use key={field.id}, the stable id that useFieldArray generates for each row.
Exercise
You need a form for a list of email tags stored as string[]. Why does useFieldArray not work directly, and how do you adapt it?
Show answer
useFieldArray supports only arrays of objects. Store the tags as { value: string }[] in the form, register each input as tags.${index}.value, and map the result to string[] in onSubmit, for example with values.tags.map((tag) => tag.value). A Zod transform can do the same conversion.