Formik

Language: JavaScript

Form Handling

Formik was created by Jared Palmer to address the complexity of handling forms in React applications. It provides a declarative API to manage form state, validation, and submission, integrating seamlessly with Yup for schema-based validation.

Formik is a popular React library for building and managing forms with ease. It simplifies form state management, validation, and submission handling while reducing boilerplate code.

Installation

npm: npm install formik
yarn: yarn add formik

Usage

Formik provides a `useFormik` hook and `<Formik>` component to manage form state. It tracks values, errors, touched fields, and submission status. You can integrate with validation libraries like Yup and customize field components using `<Field>` or `useField`.

Simple form with useFormik

import { useFormik } from 'formik';

function MyForm() {
  const formik = useFormik({
    initialValues: { email: '' },
    onSubmit: values => console.log(values)
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <input
        name='email'
        type='email'
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <button type='submit'>Submit</button>
    </form>
  );
}

Creates a simple form that tracks a single email field and logs submitted values.

Using <Formik> component with render props

import { Formik, Form, Field } from 'formik';

<Formik initialValues={{ name: '' }} onSubmit={values => console.log(values)}>
  {() => (
    <Form>
      <Field name='name' placeholder='Name' />
      <button type='submit'>Submit</button>
    </Form>
  )}
</Formik>

Demonstrates using the `<Formik>` component with `Form` and `Field` components for declarative form building.

Form validation with Yup

import * as Yup from 'yup';
import { useFormik } from 'formik';

const validationSchema = Yup.object({
  email: Yup.string().email('Invalid email').required('Required')
});

const formik = useFormik({
  initialValues: { email: '' },
  validationSchema,
  onSubmit: values => console.log(values)
});

Integrates Yup schema validation with Formik to validate form fields.

Custom input component using useField

import { useField } from 'formik';

function MyTextInput({ label, ...props }) {
  const [field, meta] = useField(props);
  return (
    <div>
      <label>{label}</label>
      <input {...field} {...props} />
      {meta.touched && meta.error ? <div>{meta.error}</div> : null}
    </div>
  );
}

Shows how to create reusable custom input components with Formik’s `useField` hook.

Handling multiple fields

const formik = useFormik({
  initialValues: { firstName: '', lastName: '' },
  onSubmit: values => console.log(values)
});
<input name='firstName' onChange={formik.handleChange} value={formik.values.firstName} />
<input name='lastName' onChange={formik.handleChange} value={formik.values.lastName} />

Manages multiple form fields in a single form using Formik.

Error Handling

Field value not updating: Ensure the field is registered correctly with `name` attribute and connected via `useField` or `handleChange`.
Validation errors not showing: Check that `validationSchema` is correctly passed and that error messages are rendered in JSX.
Form submission not triggered: Make sure `onSubmit` is passed and the form element calls `handleSubmit`.

Best Practices

Use Yup for schema-based validation for cleaner and maintainable validation logic.

Leverage `useField` or `<Field>` for reusable custom input components.

Keep forms controlled via Formik to manage all state centrally.

Validate only on blur or submit to reduce unnecessary re-renders.

Use Formik context to access form state in deeply nested components.