Blog>
Snippets

Optimizing Form Performance with Memoization

Provide an example of using memoization to prevent unnecessary re-renders of form fields in a TanStack Form.
import React from 'react';
import { useForm, useFieldArray } from 'react-tanstack-form';
Import necessary hooks from react-tanstack-form.
const FormField = React.memo(({ register, name, defaultValue }) => (
  <input {...register(name)} defaultValue={defaultValue} />
));
Define a memoized form field component to prevent unnecessary re-renders.
const MyForm = () => {
  const { register, control } = useForm();
  const { fields } = useFieldArray({
    control,
    name: 'users'
  });

  return (
    <form>
      {fields.map((field, index) => (
        <FormField
          key={field.id}
          register={register}
          name={`users[${index}].name`}
          defaultValue={field.name}
        />
      ))}
    </form>
  );
};
Use the useForm and useFieldArray hooks from TanStack Form along with the memoized FormField component to render an optimized form.