</> useFormContext:
Function
This custom hook allows you to access the form context. useFormContext
is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop.
Return
This hook will return all the useForm return methods and props.
const methods = useForm()<FormProvider {...methods} /> // all the useForm return propsconst methods = useFormContext() // retrieve those props
RULES
You need to wrap your form with the FormProvider
component for useFormContext
to work properly.
Example:
import React from "react"import { useForm, FormProvider, useFormContext } from "react-hook-form"export default function App() {const methods = useForm()const onSubmit = (data) => console.log(data)const { register, reset } = methods;useEffect(() => {reset({name: 'data'})}, [reset]); // ❌ never put `methods` as the depsreturn (<FormProvider {...methods}>// pass all methods into the context<form onSubmit={methods.handleSubmit(onSubmit)}><NestedInput /><input {...register('name')} /><input type="submit" /></form></FormProvider>)}function NestedInput() {const { register } = useFormContext() // retrieve all hook methodsreturn <input {...register("test")} />}
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.