Introduction to Formik
Learn how Formik makes it easier to create React forms.
Issues with creating forms in React
Let’s explore some of the problems that can arise during the various stages of form development in React, particularly when dealing with larger forms.
Managing the form state
When creating a React form the traditional way, we need to set up states to keep track of the values
and errors
in each of our form fields. We also need to keep track of the touched
state so we know the input fields that have been visited.
As the form gets bigger, we have more fields, and this increases the size of our state. This is because for each field we’re tracking, at least three states—the value
of the field, the touched
state, and the error
state. All of these states make the form more difficult to manage.
Validating form values
We used multiple if
statements to test for different possible validation constraints of each field. More fields in our form mean more validation constraints. This means we’ll have even more if
and nested if
statements. You can imagine how complicated our code base becomes when this happens.
Submitting the form
If we disable the default validation behavior of our form using the novalidate
attribute in the <form>
tag, clicking the “Submit” button submits the form whether or not error messages are displayed. To fix this, we have to call the submission logic conditionally. We can write a condition that ensures there are no error messages in any of the fields in the state and no invalid fields.
Get hands-on with 1400+ tech skills courses.