DEV Community 👩‍💻👨‍💻

Cover image for Efficient way of building forms with React-Hook-Form
Damian Piwowarczyk
Damian Piwowarczyk

Posted on • Updated on

Efficient way of building forms with React-Hook-Form

Building reusable forms can be sometimes challenging. In this tutorial, I will demonstrate how we can build reusable form components with the implementation of react useForHook.
We will use next.js boilerplate for this example.


React Hook Form

React Hook Form adopts the use of uncontrolled inputs using ref instead of depending on the state to control the inputs. This approach makes the forms more performant and reduces the number of re-renders.

The package is small in size and has zero dependencies. The API is well documented and provides a seamless experience to developers when working with forms. React Hook Form follows HTML standards for validating the forms using constraint-based validation API.


Create next.js project

npx create-next-app nextjs-useformhook &&
cd nextjs-useformhook && npm i react-hook-form
Enter fullscreen mode Exit fullscreen mode


Project Setup

mkdir components && cd components && mkdir Form && cd Form && touch InputField.js && touch LoginForm.js
Enter fullscreen mode Exit fullscreen mode

First, we will start with creating InputField component with some props and register function that will allow applying validation rules to our input element.

export const InputField = ({ label, register, type, error }) => (
      style={{ background: 'gray' }}
Enter fullscreen mode Exit fullscreen mode

Now we will look at implementing out LoginForm where we can reuse our InputField component.

import { useForm } from 'react-hook-form'
import { InputField } from './InputField'

export const LoginForm = () => {
  const {
    formState: { errors },
  } = useForm()

// This will contain all form data once submit button is clicked.
  const onSubmit = (data) => {
    // {Email: '', Password: 'secret'}

  register('Email', { required: { value: true, message: 'Email is required' } })
  register('Password', {
    required: { value: true, message: 'Password is required' },
  return (
      <form id='loginForm' onSubmit={handleSubmit(onSubmit)}>
      <button style={{ background: '#5757ff' }} type='submit' form='loginForm'>
Enter fullscreen mode Exit fullscreen mode

To sum up, why use react-form-hook ?
React form hook can help save us time when creating complex forms, increase our application performance by preventing unnecessary re-renderings, and help to manage validation.

Github repo

Top comments (0)

Build Anything...

Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. 👀

Join the Hackathon <-