Capítulo 30 de 39

Chapter 30: FieldArray

Core Idea

FieldArray (7.81.0+) is useFieldArray packaged as a headless render-prop component: same props, same return shape (fields, append, prepend, insert, swap, move, update, replace, remove), delivered through a render callback instead of a hook call.

Key Concepts

  • render (required): receives the exact object useFieldArray returns and must return a React element.
  • Same rules as useFieldArray: field.id (not index) as the component key, no flat/primitive arrays, shouldUnregister: true unsupported, mutation calls need full (non-partial) row objects.
  • render runs on every render: keep it free of side effects — it's not a lifecycle hook.
  • disabled: same hook-level disable semantics as useFieldArrayfields stays populated with disabled: true per entry, mutation methods become no-ops.

Code Examples

<FieldArray
  control={control}
  name="test"
  render={({ fields, append, remove }) => (
    <>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input {...register(`test.${index}.value`)} />
          <button type="button" onClick={() => remove(index)}>Delete</button>
        </div>
      ))}
      <button type="button" onClick={() => append({ value: "" })}>Append</button>
    </>
  )}
/>
  • What it demonstrates: the same field-array loop as useFieldArray, expressed declaratively as a render prop.

Anti-patterns

  • Putting side effects (fetches, state updates outside the array) inside render: it fires on every render, not on a lifecycle event.
  • Same useFieldArray anti-patterns apply: index as key, partial mutation payloads, shouldUnregister: true.

Key Takeaways

  1. FieldArray and useFieldArray are interchangeable — pick based on whether a render-prop or a hook fits the surrounding component better.
  2. Everything documented for useFieldArray's rules and mutation methods carries over unchanged.

Connects To

  • usefieldarray: the hook this component wraps; full rules/method reference lives there.
  • useform-register: how each row's inputs get registered inside the render callback.