T
TanStack2mo ago
foreign-sapphire

Best practice to use form.Subscribe in parent component?

I have a component which handles a form (created with useForm) and returns a <form>:
// MyForm.tsx
const form = useForm({
...
});

return (
<form>
<form.Field>...</form.Field>
</form>
)
// MyForm.tsx
const form = useForm({
...
});

return (
<form>
<form.Field>...</form.Field>
</form>
)
Now I want to build the parent component where I would like to subscribe to the form to dynamically render a chart based on the values in the form.
// parent.tsx
return (
<MyForm />
<form.Subscribe>
{(state) => {
const data = state.values;
...
}
</form.Subscribe>
)
// parent.tsx
return (
<MyForm />
<form.Subscribe>
{(state) => {
const data = state.values;
...
}
</form.Subscribe>
)
What is the best way to do this?
3 Replies
exotic-emerald
exotic-emerald2mo ago
this is the wrong flow for React. Props are passed from the top down, not in reverse. So assuming that the parent needs data from the form, it would be the owner of the useForm call. The child would then be responsible for the visual display + state update of the form, right?
exotic-emerald
exotic-emerald2mo ago
If so, then the Form Composition section is worth checking out: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition It lets you split up forms into multiple files / components without losing type safety. The returned form from useForm is stable, so if you have concerns with rerendering the parent, it should be no problem
Form Composition | TanStack Form React Docs
A common criticism of TanStack Form is its verbosity out-of-the-box. While this can be useful for educational purposes helping enforce understanding our APIs it's not ideal in production use cases. As...
foreign-sapphire
foreign-sapphireOP2mo ago
yeah I‘m aware of this flow. I already tried putting the useForm and the return in the parent component and pass it in a whole down to the components, but had problems with correct typing. so maybe this is worth checking out ty!

Did you find this page helpful?