Max RozenMax Rozen

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)}>
          required: 'Required',
          pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            message: 'invalid email address',
      { &&}

          validate: (value) => value !== 'admin' || 'Nice try!',
      {errors.username && errors.username.message}

      <button type="submit">Submit</button>

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.

Do you struggle to keep up with best practices in React?

I send a single email weekly with an article like this one to help improve the quality of your React apps. Lots of developers like them, and I'd love to hear what you think as well. You can always unsubscribe.

    Join 158 React developers who signed up last month!


    © 2020 Max Rozen. All rights reserved.