...

/

Manage the Form State with useFormik

Manage the Form State with useFormik

Learn how to track changes in a React form with the useFormik hook.

We'll cover the following...

A plain HTML form can accept values, but it doesn't keep track of the values in a single state. In React, the standard way to track form values is by creating a state with initial values and updating this state whenever a field's value is updated. This is how useFormik does it.

Press + to interact
Managing the form state
Managing the form state

Let's update our form to track the values of the form in a central state with useFormik.

* {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  transition: 0.6s;
}

section {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  margin-top: 4rem;
}

h1 {
  font-weight: 800;
  font-size: 2.2rem;
  color: #303170;
  margin-bottom: 0.8rem;
}

p {
  color: #74728a;
  font-weight: 500;
}

form {
  margin: 3rem 0;
}

label {
  font-size: 0.875rem;
  color: #2e2d44;
  font-weight: 600;
}

input {
  display: block;
  width: 100%;
  margin-bottom: 1.4rem;
  border-radius: 8px;
  padding: 12px 16px;
  border: 1px solid #ececec;
  outline: none;
  margin-top: 0.4rem;
  font-size: 1rem;
}

input:focus {
  border-color: #303170;
}
button {
  background: #5f30e1;
  border-radius: 8px;
  padding: 12px 20px;
  outline: none;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
  font-weight: 600;
  font-size: 14px;
  line-height: 22px;
  color: #ffffff;
  margin-top: 2rem;
  cursor: pointer;
}

button:hover {
  background: #303170;
}
How to manage the form state with useFormik

Explanation

The first thing we do in the ReservoForm.js file is to import the useFormik hook from formik. From line 4 to line 12, we call the useFormik ...