| title | useFormContext |
|---|---|
| description | React Context API for hook form |
| sidebar | apiLinks |
<SelectNav options={[ { label: "FormProvider", value: "/docs/formprovider", }, ]} />
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.
This hook will return all the useForm return methods and props.
const methods = useForm()
<FormProvider {...methods} /> // all the useForm return props
const methods = useFormContext() // retrieve those propsIf you need to subscribe to form state values like errors, isDirty, or
dirtyFields inside a FormProvider tree, use
useFormState instead of destructuring formState
from useFormContext(). formState is wrapped with a Proxy, so you should
read the specific state you want to subscribe to before render.
Example:
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 deps
return (
<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 methods
return <input {...register("test")} />
}