Member-only story

useFormContext — Deeply nested form

Vinodh Thangavel
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 with username input and submit 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 the register 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…

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet