Best practices for sharing form values between multiple forms
Hi everyone
We're currently in the process of refactoring a legacy React application and are looking for best practices for sharing values between multiple forms on a single page.
Use Case
We have a page with six forms, toggled via radio buttons. Each form:
- Queries a different data source
- Has its own unique input fields
- Shares five common fields with the other forms
- The shared fields should persist across form switches. For example, if a user fills out the shared fields in Form A and then switches to Form B, those values should carry over seamlessly.
Current Setup
Right now the forms are completely custom made per screen and Redux is being used to manage all application states. This leads to excessive re-renders and a suboptimal UX/DX - especially with larger, more complex forms.
New Setup
- TanStack Query + Axios for async state management
- TanStack Form + Zod for form state and validation
So far, we’ve refactored two single form pages and are really enjoying the improved developer experience especially with form composition. The UX has also improved drastically.
But we're not sure how to implement this use case cleanly, I would really appreciate some advice.
6 Replies
optimistic-gold•2mo ago
groups of fields that should be the same across multiple forms is not currently part of form composition. There is a PR for it that is essentially ready to merge, but it is not released yet.
As for seamless transitions for those specific fields, I‘m not entirely sure. It could be tricky to transfer meta state over since it‘s bound to the form hook, not the field. The values themselves shouldn‘t be a big deal though.
correct-apricotOP•2mo ago
Not a big deal without groups of fields 😄
I guess just the values is good enough. How would you store/update the shared values? Can't really push them into redux with onChange, otherwise you're back to the mass rerendering.
Pushing all the form values into Redux onSubmit would be fine I guess, but that's rather for keeping all the form values after a refresh
optimistic-gold•2mo ago
well, it depends on what your current component tree looks like. Where do the six forms live relative to each other and the radio buttons?
one way that came to mind is using session storage. Load it once on mount, then use a form listener to save it on field changes
alternatively, some ref that lives outside of the forms which you can call on change instead
correct-apricotOP•2mo ago
They are all on the same level just below the radio buttons, the 6 radio buttons basically just switch the current form to another form.
I guess we are still kinda stuck in the "everything into redux" mentality. Thanks for the tips
optimistic-gold•2mo ago
No problem 👍 let me know if you encounter problems during implementation
correct-apricotOP•2mo ago
Thanks, will do