Interview frequency: …
Short answer
Use React Hook Form's useFieldArray to add, remove, and move fields dynamically, giving each field a stable, unique Key.
Explanation
Invoice and task-list forms often need fields added or removed while being completed. Managing an array of objects with useState can cause focus and performance problems on deletion. useFieldArray provides append, remove, and move methods, managing key identity through the generated field.id.
Code example
import { useForm, useFieldArray } from 'react-hook-form';
function InvoiceForm() {
const { control, register } = useForm();
const { fields, append, remove } = useFieldArray({ control, name: 'items' });
return (
<div>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`items.${index}.name`)} />
<button type="button" onClick={() => remove(index)}>Delete</button>
</div>
))}
<button type="button" onClick={() => append({ name: '' })}>Add class</button>
</div>
);
}Common mistakes
- Using the array index as the Key for dynamic fields, mixing up field contents and values when a middle row is deleted.