Do you put watch value into state for react-hook-form?

In short, no. Unless you need to put your watch value into state in a react-hook-form.

React-hook-form has the watch function, so you don’t necessarily need to control your forms (causing unwanted re-renders).

The whole point of using the react-hook-form is to let react-hook-form manage your form (and its data).

Once you’ve created a form and have registered your form fields, you can assign a local variable to the value of a watched field:

const myVar = watch('myVarFieldName')

In the scheme of a component, this might look like this:

import React from 'react';
import { useForm, Controller } from 'react-hook-form';

function MyComponent() {
    const { control, handleSubmit, watch } = useForm();

    // Here we are storing the firstName form field value
    // There is no need to put this into state
    const firstName = watch('firstName'); 

    // Dummy submit function
    const onSubmit = (data) => {
        console.log(data);
    };

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <div>
                <label>First Name:</label>
                <Controller
                    name="firstName"
                    control={control}
                    defaultValue=""
                    render={({ field }) => <input {...field} />}
                />
            </div>
            <div>
                <label>Last Name:</label>
                <Controller
                    name="lastName"
                    control={control}
                    defaultValue=""
                    render={({ field }) => <input {...field} />}
                />
            </div>
            {/* Display something based on the value of the first name */}
            {firstName === 'John' ? (
                <p>Hello, John!</p>
            ) : (
                <p>Hello, {'Stranger'}!</p>
            )}
            <button type="submit">Submit</button>
        </form>
    );
}

export default MyComponent;

If you were to put the value returned from the watch function into a state variable, you would affect performance and cause more renders than you are probably expecting. You must also ensure that your state value is kept in sync with your watch value.

In short, you don’t need to add your watched values into your components state. And you really shouldn’t need to.

Source Code

I have uploaded the source code if you want to run an example of the above form. You can find it on my GitHub account. Don’t forget to star the repo!

Don’t forget to check out my React page here, which contains links to common concepts and examples in React.

Also, you can follow me on Twitter/X here! And now, mastodon: @bernieslearnings@mastodon.social

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments