Member-only story
useFormContext — Deeply nested form
2 min readJul 8, 2023
Powerful way to access form in the deeply nested child
First lets the non context way, which needs property drilling
export default function App() {
const { register, handleSubmit } = useForm({});
const onSubmit = (values) => {
console.log(values);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" {...register('username')} placeholder="username" />
<Child1 register={register} />
<button type="submit">Submit</button>
</form>
);
}
const Child1 = ({ register }) => {
return <Child2 register={register} />;
};
const Child2 = ({ register }) => {
return (
<input type="password" {...register('password')} placeholder="password" />
);
};
Structure —
- Parent component, where
form
is declared along withusername
input andsubmit
button. - Child1 component is just consuming the Child2 component. (There is a reason to do this)
- Child2 component is having the
password
input and that is where we need to use theregister
from the parent component
The above example, works fine and when clicking submit, both username and password is logged in the console, but the biggest problem is props drilling, Child1 is not consuming the props register, still it has to pass through it.
With useFormContext
import React from 'react';
import './style.css';
import { useForm, FormProvider…