Blog>
Snippets

Optimizing Form Performance

Outline strategies for optimizing form re-renders in Solid.js with TanStack Form, including the use of memoization and reactive primitives for efficient updates.
import { createForm } from 'tanstack-solid-form';
import { createSignal, createMemo } from 'solid-js';

// Define your form schema using Zod for validation (assumed imported)
const schema = Zod.object({
  name: Zod.string(),
  email: Zod.string().email()
});

// Initialize the form with TanStack Form and validation schema
const [form] = createForm({
  validate: schema.parse,
  onSubmit: async (values) => console.log(values),
});
This code snippet demonstrates the initialization of a form using the TanStack Form library in a Solid.js environment. It utilizes Zod for schema validation to ensure type safety.
const [inputValue, setInputValue] = createSignal('');

// Memoized form field to prevent unnecessary re-renders
const memoizedInput = createMemo(() => inputValue());

// Update form field value only when necessary
const handleInputChange = (e) => {
  const value = e.target.value;
  setInputValue(value);
  form.fields.name[0].field.setValue(value);
};
This code introduces a memoized input field state using Solid.js reactive primitives, illustrating how to efficiently update form state with minimal re-renders through memoization.