Sobes.tech
Middle+

Tell about React Hook Form: main features, how it is used, how validation works?

sobes.tech AI

Answer from AI

React Hook Form is a library for managing forms in React that uses hooks for simple and efficient form state control.

Main features:

  • Managing form state without the need to create controlled components.
  • Support for validation based on schemas (e.g., with Yup) or built-in rules.
  • Minimal re-renders to improve performance.
  • Easy integration with UI libraries.

Usage:

import { useForm } from 'react-hook-form';

function MyForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('username', { required: 'Name is required' })} />
      {errors.username && <p>{errors.username.message}</p>}

      <input type="submit" />
    </form>
  );
}

Validation works through passing rules to the register function or via external schemas. When submitting, handleSubmit checks the data, and if there are errors, they are accessible in formState.errors. This makes it easy to display error messages and block form submission with invalid data.

Tell about React Hook Form: main features, how it is… - sobes.tech