Submit forms in React with Formik — And how to use it with React-Query

Kyle Le
3 min readApr 4, 2021

--

We all know writing forms is very tiring. It’s verbose and boring. So form helpers are made to be less time-consuming and fun to code, but they often have performance cost associated with them. Formik is a small library that helps us, the programmers with 3 significant parts :

  1. Handling values change in form state
  2. Handling validation and error messages
  3. Handling form submission

Installation

You can install formik with Yarn or NPM :

npm install formik

or

yarn add formik

How to use

Formik only need 1 component in order to make it work, it’s Formik , but I’m here to make your life easier and the code less verbose. So let’s include <Form />, <Field />, and <ErrorMessage /> :

First, let’s take a look at my example, then I will explain all the details :

In order to use Formik. We wrap the form inside the <Formik > component. This is a simple form with 2 field : Name, Skills. And you can pass the default value of each field into the initialValues prop.

Next is validate . The form can be submitted, but the users don’t know which fields are required. So in the example above I wrote the validation for the “name” field to be required.

For the onSubmit props, we would pass functions in there so when we submit a form, the code inside the prop would run. In here, the editNinja function is a PUT Request for editing the data with 2 attributes : Name and Skills.

Next is the form itself. We use the <Form> component to create the form which is basically a simple form tag. The <Field> and the <ErrorMessage> are the last components that I would explain. The <Field> component is actually an input tag for a field. And the <ErrorMessage> will display the error whenever we change value in the field ( if it has errors )

Let’s try it out, fill the Name and Skills fields and then submit. Now look at the request payload :

Yeah now the form works perfectly when we submit. Now let’s integrate it with React-Query. First, let’s fetch the Ninja’s data with React-Query before using a form :

With the code above. We’ll get the Name and the Skills of the Ninja using the useQuery hook of React-Query

Then to change the Ninja’s information, we need to use the useMutation hook of the React-Query library

And then mutate it when we submit a form in Formik component :

The Request payload when we submit is still the same, but we would receive the updated data right away when we submit a form:

That is it ! Hope you guys can learn the basic of Formik and how to use it with React-Query !

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

--

--

Kyle Le
Kyle Le

Written by Kyle Le

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day

Responses (1)