Blog>
Snippets

Avoiding Re-renders with Memoization

Example showing how to prevent unnecessary re-renders in a form by memoizing components and utilizing TanStack Form's optimized state management.
const MemoizedInput = React.memo(({ value, onChange }) => (
  <input value={value} onChange={onChange} />
));
Defines a MemoizedInput component using React.memo to prevent unnecessary re-renders. This component will only re-render if the 'value' or 'onChange' props change.
function FormComponent() {
  const { register, formState } = useForm();
  const handleSubmit = (data) => console.log(data);
  
  return (
    <form onSubmit={handleSubmit}>
      <MemoizedInput {...register('firstName')} />
      <button type='submit'>Submit</button>
    </form>
  );
}
Implements the FormComponent using TanStack Form's useForm hook for form management. It uses the MemoizedInput component for the 'firstName' field to prevent unnecessary re-renders triggered by unrelated state changes.
function App() {
  return (
    <div>
      <FormComponent />
    </div>
  );
}
Sets up a simple App component that renders the FormComponent. This structure demonstrates how the MemoizedInput field can be used within a larger application context.