Blog>
Snippets

Optimizing Large Forms Performance

Provide an example of using memoization techniques within a TanStack form to prevent unnecessary rerenders thus optimizing performance in large or complex forms.
import { useMemo } from 'react';
import { useForm, useField } from '@tanstack/react-form';
First, import useMemo from React for memoization, and useForm and useField from @tanstack/react-form to handle the form and fields.
const OptimizedField = ({ fieldKey, form }) => {
  const field = useField(form, fieldKey);
  return useMemo(() => (
    <div>
      <input {...field.getInputProps()} />
      {field.meta.error && <span>{field.meta.error}</span>}
    </div>
  // Only re-render if field error or value changes
  ), [field.meta.error, field.state.value]);
};
Defines an OptimizedField component that utilizes useMemo to prevent unnecessary re-renders. It re-renders only if the field's error message or value changes.
function MyForm() {
  const form = useForm({
    defaultValues: { name: '', email: '' },
  });

  return (
    <form onSubmit={form.handleSubmit(values => console.log(values))}>
      <OptimizedField fieldKey='name' form={form} />
      <OptimizedField fieldKey='email' form={form} />
      <button type='submit'>Submit</button>
    </form>
  );
}
Creates a form using the useForm hook and utilizes the OptimizedField for each field, which helps prevent unnecessary renders.