Course contentsShow
← React
Lesson 1229 of 2,39631. Forms in ReactFree lesson

Formik's Core API: useFormik Hook

The basic useFormik hook pattern with initialValues, onSubmit, and handleChange.

Formik's Core API: useFormik Hook

You'll learn how to use Formik's useFormik hook to manage form state with just three key properties: initialValues, onSubmit, and helpers like handleChange.

The Core Pattern

The useFormik hook is Formik's foundation. It takes a configuration object and returns an object containing everything you need to wire up a form: values, handlers, and submission logic. Think of it as a "form state manager in a box" — you describe your form's shape and behavior, and Formik handles the wiring.

Unlike React Hook Form's register() approach, Formik uses explicit value and onChange bindings on each input, making it a controlled component pattern under the hood.

The Three Essential Pieces

import { useFormik } from 'formik';

function LoginForm() {
  const formik = useFormik({
    // 1. Initial state for each field
    initialValues: {
      email: '',
      password: ''
    },

    // 2. What happens when form submits
    onSubmit: (values) => {
      console.log('Form submitted:', values);
      // values is type-safe and matches initialValues shape
    }
  });

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

The handleChange helper automatically updates the right field based on the input's name attribute — no manual state updates needed. The values object always reflects your current form state.

Key Takeaway: useFormik bundles form state (values), change handlers (handleChange), and submission logic (handleSubmit) into one hook, using a fully controlled pattern that feels more manual than React Hook Form but offers explicit control over each input.