Convert Figma logo to code with AI

TanStack logoform

🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.

3,629
325
3,629
57

Top Related Projects

33,863

Build forms in React, without the tears 😭

📋 React Hooks for form state management and validation (Web + React Native)

🏁 High performance subscription-based form state management for React

4,460

Performance-focused API for React forms 🚀

Quick Overview

TanStack Form is a powerful, type-safe, and flexible form management library for React applications. It provides a headless UI approach, allowing developers to build complex forms with custom UI components while handling state management, validation, and submission logic efficiently.

Pros

  • Type-safe: Leverages TypeScript for strong typing and improved developer experience
  • Flexible: Headless UI approach allows for complete control over form rendering
  • Performance-oriented: Optimized for minimal re-renders and efficient state updates
  • Comprehensive: Handles complex form scenarios, including nested fields and arrays

Cons

  • Learning curve: May require time to understand the API and concepts
  • Verbose setup: Initial configuration can be more complex compared to simpler form libraries
  • Limited ecosystem: Being relatively new, it has fewer third-party integrations and resources compared to more established libraries

Code Examples

  1. Basic form setup:
import { useForm } from '@tanstack/react-form'

function MyForm() {
  const form = useForm({
    defaultValues: {
      firstName: '',
      lastName: '',
    },
    onSubmit: async ({ value }) => {
      // Submit form data
      console.log('Form submitted:', value)
    },
  })

  return (
    <form.Provider>
      <form onSubmit={form.handleSubmit}>
        <form.Field
          name="firstName"
          children={(field) => (
            <input
              placeholder="First Name"
              value={field.state.value}
              onBlur={field.handleBlur}
              onChange={(e) => field.handleChange(e.target.value)}
            />
          )}
        />
        <form.Field
          name="lastName"
          children={(field) => (
            <input
              placeholder="Last Name"
              value={field.state.value}
              onBlur={field.handleBlur}
              onChange={(e) => field.handleChange(e.target.value)}
            />
          )}
        />
        <button type="submit">Submit</button>
      </form>
    </form.Provider>
  )
}
  1. Form with validation:
import { useForm } from '@tanstack/react-form'

function MyFormWithValidation() {
  const form = useForm({
    defaultValues: {
      email: '',
    },
    onSubmit: async ({ value }) => {
      console.log('Form submitted:', value)
    },
  })

  return (
    <form.Provider>
      <form onSubmit={form.handleSubmit}>
        <form.Field
          name="email"
          validators={{
            onChange: ({ value }) => {
              if (!value.includes('@')) {
                return 'Invalid email address'
              }
            },
          }}
          children={(field) => (
            <>
              <input
                placeholder="Email"
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
              />
              {field.state.meta.touchedErrors ? (
                <span>{field.state.meta.touchedErrors}</span>
              ) : null}
            </>
          )}
        />
        <button type="submit">Submit</button>
      </form>
    </form.Provider>
  )
}

Getting Started

To start using TanStack Form, first install the package:

npm install @tanstack/react-form

Then, import and use the useForm hook in your React component:

import { useForm } from '@tanstack/react-form'

function MyForm() {
  const form = useForm({
    defaultValues: {
      // Your form's initial values
    },
    onSubmit: async ({ value }) => {
      // Handle form submission
    },
  })

  return (
    <form.Provider>
      {/* Your form fields and UI components */}
    </form.Provider>
  )
}

Refer to the official documentation for more detailed usage instructions and advanced features.

Competitor Comparisons

33,863

Build forms in React, without the tears 😭

Pros of Formik

  • More mature and widely adopted in the React ecosystem
  • Extensive documentation and community support
  • Built-in integration with popular validation libraries like Yup

Cons of Formik

  • Larger bundle size compared to TanStack Form
  • More opinionated approach, which may limit flexibility in some cases
  • Performance can degrade with complex forms or large datasets

Code Comparison

Formik:

import { Formik, Form, Field } from 'formik';

<Formik initialValues={{ name: '' }} onSubmit={handleSubmit}>
  <Form>
    <Field name="name" />
    <button type="submit">Submit</button>
  </Form>
</Formik>

TanStack Form:

import { useForm } from '@tanstack/react-form'

const form = useForm({
  defaultValues: { name: '' },
  onSubmit: handleSubmit,
})

<form.Provider>
  <form onSubmit={form.handleSubmit}>
    <input {...form.register('name')} />
    <button type="submit">Submit</button>
  </form>
</form.Provider>

Both libraries aim to simplify form management in React applications, but they differ in their approach and feature set. Formik offers a more comprehensive solution with built-in components and integrations, while TanStack Form provides a lightweight and flexible alternative with a focus on performance and customization.

📋 React Hooks for form state management and validation (Web + React Native)

Pros of react-hook-form

  • Lightweight and performant, with minimal re-renders
  • Extensive documentation and large community support
  • Easy integration with existing form elements and third-party UI libraries

Cons of react-hook-form

  • Less flexible for complex form state management
  • Limited built-in validation options compared to TanStack Form
  • Steeper learning curve for advanced use cases

Code Comparison

react-hook-form:

import { useForm } from 'react-hook-form';

const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName")} />
  <input type="submit" />
</form>

TanStack Form:

import { useForm } from '@tanstack/react-form'

const form = useForm({
  defaultValues: { firstName: '' },
  onSubmit: async (values) => console.log(values),
})

<form.Provider>
  <form onSubmit={form.handleSubmit}>
    <form.Field name="firstName" children={field => (
      <input {...field.props} />
    )} />
    <button type="submit">Submit</button>
  </form>
</form.Provider>

Both libraries offer efficient form handling in React applications. react-hook-form excels in simplicity and performance for basic to intermediate forms, while TanStack Form provides more advanced features and flexibility for complex form scenarios. The choice between them depends on the specific requirements of your project and the level of control you need over form state and validation.

🏁 High performance subscription-based form state management for React

Pros of react-final-form

  • Mature and battle-tested library with a large community
  • Extensive documentation and examples available
  • Supports both synchronous and asynchronous validation out of the box

Cons of react-final-form

  • Larger bundle size compared to form
  • Less flexible API for complex form scenarios
  • Steeper learning curve for advanced use cases

Code Comparison

react-final-form:

import { Form, Field } from 'react-final-form'

<Form
  onSubmit={onSubmit}
  render={({ handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      <Field name="firstName" component="input" />
    </form>
  )}
/>

form:

import { useForm } from '@tanstack/react-form'

const form = useForm({
  defaultValues: { firstName: '' },
  onSubmit: async (values) => {
    // Handle submission
  },
})

<form.Field
  name="firstName"
  children={(field) => <input {...field.getInputProps()} />}
/>

Both libraries offer robust form handling capabilities, but form provides a more modern and flexible approach with its hook-based API. react-final-form has the advantage of being more established and having extensive documentation, while form offers a smaller bundle size and a more intuitive API for complex scenarios. The choice between the two depends on specific project requirements and developer preferences.

4,460

Performance-focused API for React forms 🚀

Pros of Unform

  • Simpler API with less boilerplate code
  • Built-in integration with popular UI libraries like React Native and Material-UI
  • Strong focus on performance optimization

Cons of Unform

  • Less flexibility for complex form scenarios
  • Smaller community and ecosystem compared to TanStack Form
  • Limited documentation and examples for advanced use cases

Code Comparison

Unform:

import { Form } from '@unform/web';

function MyForm() {
  return (
    <Form onSubmit={handleSubmit}>
      <Input name="email" />
      <Input name="password" type="password" />
      <button type="submit">Submit</button>
    </Form>
  );
}

TanStack Form:

import { useForm } from '@tanstack/react-form';

function MyForm() {
  const form = useForm({
    defaultValues: { email: '', password: '' },
    onSubmit: handleSubmit,
  });

  return (
    <form.Provider>
      <form.Field name="email" />
      <form.Field name="password" type="password" />
      <button type="submit">Submit</button>
    </form.Provider>
  );
}

Both libraries aim to simplify form management in React applications, but they differ in their approach and feature set. Unform offers a more straightforward API with less setup required, while TanStack Form provides greater flexibility and control over form behavior.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

TanStack Form Header

Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Angular Form, Lit Form and Vue Form.

#TanStack semantic-release Join the discussion on Github Best of JS Gitpod Ready-to-Code

Enjoy this library? Try the entire TanStack! TanStack Query, TanStack Table, TanStack Router, TanStack Virtual, React Charts, React Ranger

Visit tanstack.com/form for docs, guides, API and more!

Become a Sponsor!