TanStackT
TanStackโ€ข12mo ago
skinny-azure

How to sync with external store like Zustand?

Hey there ๐Ÿ‘‹ what is the best way to sync the form store with an external store? I am using Zustand to initialize form values and also to persist form store values using Zustand's persist() middleware.

My current solution utilizes the internal Store api to subscribe to store changes. I then update the Zustand store with new store values as they come. In the following snippet, you'll see that I have tried subscribing in two ways. Directly calling subscribe outside of a useEffect causes nearly 100 store updates. The current approach only updates the store 5 times, and this may be acceptable since this causes no rendering issues (the store values are only grabbed at component mount). Here is my current solution:

export function InterviewForm({ initialPersons }: InterviewFormProps) {
  const formValues = useInterviewFormStore.getState().values;
  const updateFormValues = useInterviewFormStore((s) => s.updateValues);
  const resetForm = useInterviewFormStore((s) => s.reset);

  const form = useForm({
    defaultValues: formValues,
    onSubmit: (state) => {
      // ...
    },
    validators: {
      onSubmit: formSchema,
    },
  });

  // form.store.subscribe((state) => { // This method causes nearly 100 store updates per form state change!
  //   updateFormValues(state.currentVal.values);
  // }); 

  useEffect(() => { // This method causes 5 store updates
    return form.store.subscribe((state) => {
      updateFormValues(state.currentVal.values);
    });
  }, [form.store]);

  if (!formValues) return;

  return (
  // ...
) }


Any better solution to sync the TanStack Form store state to an external store? Keep in mind that we don't want to reactively subscribe to state changes. Hence, we don't use useStore(). We merely want to call our Zustand updater function when the store values change.
Was this page helpful?