Blog>
Snippets

Using Form Context for Global State Management in TanStack Form

Explain how to use the form context feature of TanStack Form for managing global form state, facilitating communication between deeply nested form fields.
import { useForm, FormProvider, useFormContext } from 'tanstack-form';
First, we import useForm to create a form instance, FormProvider to pass the form instance context globally, and useFormContext to consume the form context in deeply nested components.
const form = useForm({
  defaultValues: {
    username: '',
    email: ''
  }
});
Create a form instance with default values. This form instance will be provided to all the form elements wrapped in the FormProvider.
function App() {
  return (
    <FormProvider form={form}>
      <Form />
    </FormProvider>
  );
}
Wrap your form components inside FormProvider and pass the form instance. This makes the form context available to all components within.
function Form() {
  const formContext = useFormContext();
  return (
    <form>
      <input
        name="username"
        value={formContext.values.username || ''}
        onChange={e => formContext.setValue('username', e.target.value)}
      />
      <input
        name="email"
        value={formContext.values.email || ''}
        onChange={e => formContext.setValue('email', e.target.value)}
      />
    </form>
  );
}
Use useFormContext to access the form instance in deeply nested components. This allows you to bind inputs to the global form state and handle changes.