Blog>
Snippets

Optimizing Form Performance with useFieldArray

Demonstrate the use of useFieldArray hook from TanStack Form to manage dynamic form fields efficiently, emphasizing performance optimization.
import { useFieldArray, useForm } from 'react-hook-form';
First, import the necessary hooks from TanStack Form.
function DynamicForm() {
  const { control, handleSubmit } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'users'
  });
Initialize the useForm and useFieldArray hooks. 'useFieldArray' is used for managing dynamic arrays of fields.
const onSubmit = (data) => console.log(data);

  return (
    /* Form rendering logic here, showing usage of fields, append, and remove */
  );
}
Define an onSubmit function to handle form submission and log the form data. Following this, return the dynamic form component structure.
/* Example usage of append */
<button onClick={() => append({ name: '', age: '' })}>Add User</button>
Demonstrates how to add a new user object to the 'users' array field by using the 'append' method.
/* Example usage of remove */
<button onClick={() => remove(index)}>Remove User</button>
Shows how to remove a specific user from the 'users' array field using the 'remove' method. The 'index' parameter refers to the index of the user to be removed.
export default DynamicForm;
Exports the DynamicForm component for use in other parts of the application.