Context
I’m using React Hook Form together with React Query. The parent component fetches data with a query, derives defaultValues, and passes them into the form.
Parent component:
export const Agreement = ({ clientId }: { clientId: number }) => {
const { data } = useGetServiceAgreement();
const defaultValues = {
description: data.description,
clientCommissionPercent: data.clientCommissionPercent,
};
return <AgreementForm defaultValues={defaultValues} />
};
Form component:
const FORM_RESET_CONFIG = {
keepDirtyValues: true,
keepErrors: true,
keepTouched: true,
keepIsSubmitted: true,
keepSubmitCount: true,
keepIsValid: true,
} as const;
export const AgreementForm = ({
defaultValues,
}: {
defaultValues: ClientAgreementFormData;
}) => {
const methods = useForm<ClientAgreementFormData>({
resolver: yupResolver(ClientAgreementSchema),
defaultValues: defaultValues ?? ClientAgreementSchema.getDefault(),
});
const { reset, handleSubmit } = methods;
useEffect(() => {
reset(defaultValues, FORM_RESET_CONFIG);
}, [defaultValues, reset]);
const onSubmit = async (data: ClientAgreementFormData) => {};
return form
What I need
React Query may refetch on window focus (refetchOnWindowFocus: true). In that case, I want to update the form with the new server values only for fields the user hasn’t touched. I’m currently doing:
reset(defaultValues, FORM_RESET_CONFIG); // with keepDirtyValues: true, etc.
After a successful submit, I want to fully reset the form to the values returned by the server (clearing dirty/touched state):
reset(valuesFromPostResponse); // without FORM_RESET_CONFIG
Questions
Is it a good idea to sync form values with updated defaultValues when the query refetches? Any recommended best practices or pitfalls?
What’s the recommended pattern to support both flows in a single form:
Partial sync on refetch (preserving dirty fields), and full reset after a successful submit?