DEV Community

Max Rozen
Max Rozen

Posted on • Originally published at maxrozen.com

Frustrated by Formik? Here's a simpler way to do forms in React

Is this you?

I've tried so many different things I've found online

Holy crap it works now, such a small problem I've lost hours to :(

All I want to do is a simple thing, this is all so unnecessarily complex

Try using react-hook-form.

React-hook-form is different, because it (mostly) keeps its state in the DOM (like classic HTML form elements).

Here's an example of a single field form in react-hook form (taken from their docs):

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

const Example = () => {
  const { handleSubmit, register, errors } = useForm();
  const onSubmit = (values) => console.log(values);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="email"
        ref={register({
          required: 'Required',
          pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            message: 'invalid email address',
          },
        })}
      />
      {errors.email && errors.email.message}

      <input
        name="username"
        ref={register({
          validate: (value) => value !== 'admin' || 'Nice try!',
        })}
      />
      {errors.username && errors.username.message}

      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Compare that to your existing form code. I don't know about you, but my React forms with Formik would have twice as many lines of code to achieve the same thing.

You'll notice that it's using ref, rather than tracking state within the library. Since moving to react-hook-form, I no longer have to worry about state not syncing correctly in huge forms.

Everything just works as expected, and my code is much simpler too.

Shameless plug

If you'd like more tips on how to improve your frontend, you can follow me on Twitter or subscribe to my newsletter as I regularly post articles there.

Top comments (3)

Collapse
 
naismith profile image
Chris Naismith

I have been using react-hook-form for about a year now and it is fantastic. As someone who previously used Formik it was an easy switch ๐Ÿ‘Œ. Thanks for sharing this for others to see!

Collapse
 
rozenmd profile image
Max Rozen

Thank you! ๐Ÿ˜„

Collapse
 
okeeffed profile image
Dennis O'Keeffe

react-hook-forms gets all the +1s from me! Love it.