TanStackT
TanStack7mo ago
35 replies
foolish-indigo

define form api instance externally, consume via react

hello,

i'd like to define my store like

const formApi = new FormApi({...formOptions})

and still consume it inside of my react components the same way it would work if i used useForm directly. The source for useForm shows that it just creates the new FormApi instance inside of a useState lazy initializer, so it would be easy enough to create a useGlobalFormState hook that does the same thing as what's inside useForm -- but is this bad practice? is there a reason it's not built in?

my reason for wanting this is: i currently use zustand in my app to store websocket subscriptions and a separate zustand store for form state. within the websocket callback, i dispatch an action to change certain form fields in my form, without involving react renders or useEffect silliness. These actions are not user interactions but messages coming in from a websocket.

this is quite clean and avoids many problems with stale closures, dependency arrays etc, etc. But it seems this is more difficult to achieve with tanstack form. I whipped this up just now, and i think it would work https://gist.github.com/matthewdavi/2d0a6a185d85142b3538170bf6897f0e

for context, my app is fully client side with no SSR and makes heavy use of websockets for updating state
Gist
use a store defined at module scope with tanstack form - useFormApi.ts
use a store defined at module scope with tanstack form
Was this page helpful?