How to use setValue with React Hook Form

robyconte

Roberto Conte Rosito

Posted on January 18, 2023

How to use setValue with React Hook Form

My dev notes about how to set value with React Hook Form. Following the official documentationyou can set a value with React Hook Form using the setValue method to change it programmatically like this:

const { setValue } = useForm();
...
setValue("firstName", "bill");

Enter fullscreen mode Exit fullscreen mode

But this is wrong!

You have to use the setValue method to change the value of a field programmatically, but only using the useFormContext hook instead of the useForm hook:

const { setValue } = useFormContext();
...
// Somewhere inside the form
setValue("firstName", "bill");

Enter fullscreen mode Exit fullscreen mode

Remember: the first one is used during initialization of the form, the second one is used inside the form.

💖 💪 🙅 🚩
robyconte
Roberto Conte Rosito

Posted on January 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to use setValue with React Hook Form
reacthookform How to use setValue with React Hook Form

January 18, 2023