Forms are a common need for many React apps. However, managing form state and validation can be tricky.

Thankfully, React provides great libraries to simplify complex forms. Let’s explore some helpful tools:

Formik for Form State

Formik handles common form tasks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { Formik } from 'formik';

const MyForm = () => (
  <Formik
    initialValues={{ email: '' }}
    onSubmit={values => console.log(values)}
  >
    {formik => (
      <form onSubmit={formik.handleSubmit}>
        <input 
          name="email"
          onChange={formik.handleChange}
          value={formik.values.email} 
        />
        <button type="submit">Submit</button>
      </form>
    )}
  </Formik>
)

Formik reduces boilerplate for:

  • Initial values
  • Validation
  • Handling submissions
  • Dynamic form values

React Hook Form for Custom Hooks

React Hook Form uses custom hooks for forms:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { useForm } from "react-hook-form";

function MyForm() {
  const { register, handleSubmit } = useForm();
  
  const onSubmit = data => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      
      <input {...register("lastName")} />
    
      <input type="submit" />
    </form>
  );
}

Custom hooks provide flexibility without context providers.

Yup for Validation

Yup makes complex validation simple:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import * as yup from 'yup';

const schema = yup.object().shape({
  email: yup.string().email(),
  age: yup.number().positive().integer(),
});

// validate data against schema
schema.validate(data)
  .then(validData => {
    // valid! 
  })

Yup has validation methods for types, length, custom tests and more.

Summary

  • Formik manages state and submission
  • React Hook Form uses custom hooks
  • Yup validates with a schema

Leveraging great libraries helps tackle the complexity of forms in React.