DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Correct use of register and useState in React Hook Form

Introduction

When creating forms with React, you may use

  • React's useState
  • react-hook-form's register

This article explains how to use these two methods, clearly explaining their roles and differences.

useState (React Standard)

useState = Just remember the value

  • Just a "container for saving state"

  • setState → The screen is redrawn every time there's input

  • For small forms

const [name, setName] = useState("");
<input value={name} onChange={(e) => setName(e.target.value)} />
Enter fullscreen mode Exit fullscreen mode

register (react-hook-form)

register = Remember and check the value

  • A form-specific "state management and validation" tool

  • Automatically manage values ​​by simply writing register("name")

  • Great for large forms and input validation

const { register, formState: { errors } } = useForm();
<input {...register("name", { required: "Required" })} />
{errors.name && <p>{errors.name.message}</p>}
Enter fullscreen mode Exit fullscreen mode

Summary

When you want to handle changing values ​​in real time → useState

When you want to handle form input → react-hook-form's register

Using both will result in bugs, as it will be unclear which value is in which state.

Top comments (0)