Blog>
Snippets

Using TanStack Form for Global State Management

Showcase how TanStack Form can be utilized to manage global application state through an example, highlighting its benefits over traditional state management solutions.
import { useForm } from '@tanstack/react-form';
import { useState, useEffect } from 'react';
Imports useForm from TanStack Form and useState, useEffect from React.
const globalState = {};
function useGlobalForm({ initialState }) {
  const [state, setState] = useState(initialState);
  useEffect(() => {
    Object.assign(globalState, state);
  }, [state]);
  const form = useForm({
    defaultValues: initialState,
    onSubmit: async (values) => {
      setState(values);
    },
  });
  return form;
}
Defines a custom hook `useGlobalForm` for global state management using TanStack Form. It synchronizes form state with a global state object.
function MyComponent() {
  const form = useGlobalForm({ initialState: { name: '' } });
  return (
    <form onSubmit={form.handleSubmit}>
      <input {...form.register('name')} />
      <button type='submit'>Submit</button>
    </form>
  );
}
A component that uses `useGlobalForm` to manage the 'name' field. This showcases how form data can both influence and be influenced by global state.