DEV Community

Roberto Conte Rosito
Roberto Conte Rosito

Posted on • Originally published at blog.robertoconterosito.it on

10

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
nelsonsilvahubel profile image
NelsonSilvaHubel

Using the setValue of useFormContext the value of a field change programmatically but the save button of form is disabled anyway.
The save button is only enabled if i change the field manually.
Any tip to solve that? (Im using SimpleForm of react_admin)

Collapse
 
robyconte profile image
Roberto Conte Rosito

Have you checked list of touched fields when using setValue?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay