import { useEffect, useRef } from 'react'; import type { DeepPartial, FieldValues, UseFormReturn } from 'react-hook-form'; import { useWatch } from 'react-hook-form'; interface UseWatchFormProps extends Pick, 'control'>, Partial, 'reset'>> { initialValues?: F; onChange?: (values: DeepPartial) => void; } export function useWatchForm( options: UseWatchFormProps, ) { const { control, reset, initialValues, onChange } = options; const isMountedRef = useRef(false); const onChangeRef = useRef(onChange); const watchedValues = useWatch({ control }); useEffect(() => { onChangeRef.current = onChange; }, [onChange]); useEffect(() => { if (initialValues !== undefined) { isMountedRef.current = false; reset?.(initialValues); } }, [initialValues, reset]); useEffect(() => { if (isMountedRef.current) { onChangeRef.current?.(watchedValues); } isMountedRef.current = true; }, [watchedValues]); }