Skip to content
Core Concepts

Subscribing to State

When working with form fields, form.Field handles rerendering for you. Changes to the field's value or metadata cause the child component to rerender. However, form state works differently:

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

function App() {
  const form = useForm({
    defaultValues: { firstName: '' },
  })

  return (
    <>
      <form.Field name="firstName">
        {(field) => (
          <TextInput
            // You may even use memoized components / React Compiler!
            // The fresh field reference will cause it to rerender.
            field={field}
            label="First name"
          />
        )}
      </form.Field>
      {/* This button never updates, though. */}
      <button type="submit" disabled={form.state.isPristine}>
        Submit
      </button>
    </>
  )
}

Creating reactive UI

Each time you read form.state, you get the latest state. However, that read alone does not subscribe your component to future changes.

Reading form state directly is fine in event handlers or other functions:

ts
const form = useForm({
  defaultValues: { firstName: '' },
})

async function saveDraft() {
  if (form.state.isPristine) return
  await storeDraft(form.state.values)
}

If you need components to rerender when form state changes, you have two options:

form.Subscribe

This component accepts a selector and rerenders its child components whenever the selected value changes. For example, we want to disable a submit button if isDefaultValue is true. The selector looks like this:

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

function Example() {
  const form = useForm({
    defaultValues: { firstName: '' },
  })

  return (
    <>
      <form.Subscribe selector={(state) => state.isDefaultValue}>
        {(isDefaultValue) => (
          <button type="submit" disabled={isDefaultValue}>
            Submit
          </button>
        )}
      </form.Subscribe>
      {/* You can also subscribe to multiple values: */}
      <form.Subscribe
        selector={(state) => [state.isDefaultValue, state.isSubmitting]}
      >
        {([isDefaultValue, isSubmitting]) => (
          <button type="submit" disabled={isDefaultValue || isSubmitting}>
            Submit
          </button>
        )}
      </form.Subscribe>
    </>
  )
}

Showing content conditionally

Sometimes, the components you're rendering are only relevant when the subscribed state meets a condition. For simple cases, you can use the when property to render them conditionally:

tsx
<>
  {/* We only care about the state if `isSubmitSuccessful` is true */}
  <form.Subscribe selector={(state) => state.isSubmitSuccessful}>
    {(isSubmitSuccessful) =>
      isSubmitSuccessful ? <span role="alert">Submitted!</span> : null
    }
  </form.Subscribe>

  <form.Subscribe
    selector={(state) => state.isSubmitSuccessful}
    when={(isSubmitSuccessful) => isSubmitSuccessful}
  >
    {/* This will only render if isSubmitSuccessful becomes true. */}
    {(isSubmitSuccessful) => <span role="alert">Submitted!</span>}
  </form.Subscribe>

  <form.Subscribe
    selector={(state) => state.isSubmitSuccessful}
    when={(isSubmitSuccessful) => isSubmitSuccessful}
  >
    {/* We're not using the passed state, so you can use JSX directly too  */}
    <span role="alert">Submitted!</span>
  </form.Subscribe>
</>

useSelector

This hook rerenders the component that calls it whenever the selected value changes.

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

function Example() {
  const form = useForm({
    defaultValues: { firstName: '', lastName: '' },
  })

  const firstName = useSelector(form.atom, (state) => state.values.firstName)
  const lastName = useSelector(form.atom, (state) => state.values.lastName)

  // You can now create derived variables or use it in JSX
  const fullName = React.useMemo(
    () => `${firstName} ${lastName}`.trim(),
    [firstName, lastName],
  )

  return null
}

By default, useSelector compares the previous and next results using ===. You may configure other comparison functions:

ts
import { shallow, useForm, useSelector } from '@tanstack/react-form'

function Example() {
  const form = useForm({
    defaultValues: { firstName: '', lastName: '' },
  })

  // A shallow comparison will compare each element in the given array
  const bothNames = useSelector(
    form.atom,
    (state) => [state.values.firstName, state.values.lastName],
    { compare: shallow },
  )
}