| 42 | * ``` |
| 43 | */ |
| 44 | export function useForm< |
| 45 | TFieldValues extends FieldValues = FieldValues, |
| 46 | TContext = any, |
| 47 | TTransformedValues = TFieldValues, |
| 48 | >( |
| 49 | props: UseFormProps<TFieldValues, TContext, TTransformedValues> = {}, |
| 50 | ): UseFormReturn<TFieldValues, TContext, TTransformedValues> { |
| 51 | const _formControl = React.useRef< |
| 52 | UseFormReturn<TFieldValues, TContext, TTransformedValues> | undefined |
| 53 | >(undefined); |
| 54 | const _values = React.useRef<typeof props.values>(undefined); |
| 55 | const [formState, updateFormState] = React.useState<FormState<TFieldValues>>({ |
| 56 | isDirty: false, |
| 57 | isValidating: false, |
| 58 | isLoading: isFunction(props.defaultValues), |
| 59 | isSubmitted: false, |
| 60 | isSubmitting: false, |
| 61 | isSubmitSuccessful: false, |
| 62 | isValid: false, |
| 63 | submitCount: 0, |
| 64 | dirtyFields: {}, |
| 65 | touchedFields: {}, |
| 66 | validatingFields: {}, |
| 67 | errors: props.errors || {}, |
| 68 | disabled: props.disabled || false, |
| 69 | isReady: false, |
| 70 | defaultValues: isFunction(props.defaultValues) |
| 71 | ? undefined |
| 72 | : props.defaultValues, |
| 73 | }); |
| 74 | |
| 75 | if (!_formControl.current) { |
| 76 | if (props.formControl) { |
| 77 | _formControl.current = { |
| 78 | ...props.formControl, |
| 79 | formState, |
| 80 | }; |
| 81 | |
| 82 | if (props.defaultValues && !isFunction(props.defaultValues)) { |
| 83 | props.formControl.reset(props.defaultValues, props.resetOptions); |
| 84 | } |
| 85 | } else { |
| 86 | const { formControl, ...rest } = createFormControl(props); |
| 87 | |
| 88 | _formControl.current = { |
| 89 | ...rest, |
| 90 | formState, |
| 91 | }; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | const control = _formControl.current.control; |
| 96 | control._options = props; |
| 97 | |
| 98 | useIsomorphicLayoutEffect(() => { |
| 99 | const sub = control._subscribe({ |
| 100 | formState: control._proxyFormState, |
| 101 | callback: () => updateFormState({ ...control._formState }), |