Registry / web-framework / formik

formik

JSON →
library2.4.9jsnpmunverified

Formik is a popular open-source library for building forms in React, designed to streamline the notoriously complex aspects of form state management, validation, and submission. It significantly reduces boilerplate by providing a unified API through React Hooks (like `useFormik`, `useField`), Higher-Order Components (`withFormik`), and Render Props (`<Formik>`). The current stable version, 2.4.9, receives regular patch releases focusing on bug fixes, performance improvements, and compatibility with the evolving React ecosystem, including recent updates for React 19. Formik's core philosophy prioritizes performance by minimizing re-renders and offers flexible validation options, often integrating seamlessly with schema-based validation libraries like Yup. Its key differentiators include its comprehensive yet minimal API, support for multiple composition patterns, and a strong emphasis on developer experience, often chosen over alternatives for its focus on local form state rather than global state management.

npm install formik
INSTALL
IMPORT
SIG · FORMIK
F
formik
web-frameworkjavascriptv2.4.9
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Formik
import { Formik } from 'formik';
const Formik = require('formik');
Formik is primarily consumed via ES Modules. While CommonJS might work in some setups, direct named imports are the standard and recommended approach for modern React applications.
useFormik
import { useFormik } from 'formik';
import Formik from 'formik'; // then Formik.useFormik
The `useFormik` hook is a named export. Attempting to access it as a property of a default import (if one were available) or via CommonJS require is incorrect. It requires React >= 16.8.0.
Field
import { Field } from 'formik';
const Field = Formik.Field;
`Field` is a component used for connecting form inputs to Formik state and is a named export. Ensure it's imported directly.
ErrorMessage
import { ErrorMessage } from 'formik';
`ErrorMessage` is a utility component for displaying validation messages for a given field.

This quickstart demonstrates a basic sign-up form using the `useFormik` hook, `Field`, `ErrorMessage`, and `Form` components, integrated with Yup for schema-based validation. It shows how to initialize values, define validation rules, handle changes, blurs, and form submission, including an asynchronous submission example. To run this, install `formik` and `yup`.

import React from 'react'; import { useFormik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; // Often used for schema validation const SignupForm = () => { const formik = useFormik({ initialValues: { firstName: '', lastName: '', email: '', }, validationSchema: Yup.object({ firstName: Yup.string() .max(15, 'Must be 15 characters or less') .required('Required'), lastName: Yup.string() .max(20, 'Must be 20 characters or less') .required('Required'), email: Yup.string().email('Invalid email address').required('Required'), }), onSubmit: async (values, { setSubmitting, resetForm }) => { // Simulate an async submission console.log('Submitting values:', values); await new Promise(resolve => setTimeout(resolve, 500)); alert(JSON.stringify(values, null, 2)); setSubmitting(false); // Optionally reset the form after submission // resetForm(); }, }); return ( <Form onSubmit={formik.handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '10px', maxWidth: '300px', margin: '20px auto', padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}> <label htmlFor="firstName">First Name</label> <Field id="firstName" name="firstName" type="text" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.firstName} style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }} /> <ErrorMessage name="firstName" component="div" style={{ color: 'red', fontSize: '0.8em' }} /> <label htmlFor="lastName">Last Name</label> <Field id="lastName" name="lastName" type="text" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.lastName} style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }} /> <ErrorMessage name="lastName" component="div" style={{ color: 'red', fontSize: '0.8em' }} /> <label htmlFor="email">Email Address</label> <Field id="email" name="email" type="email" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }} /> <ErrorMessage name="email" component="div" style={{ color: 'red', fontSize: '0.8em' }} /> <button type="submit" disabled={formik.isSubmitting} style={{ padding: '10px 15px', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}> Submit </button> </Form> ); }; export default SignupForm;
Debug
Known issues
breakingFormik v1 to v2 introduced significant breaking changes. Key changes include a revised `resetForm` signature, deprecation of the `render` prop in favor of child callback functions for `<Formik>`, `<Field>`, `<FastField>`, and `<FieldArray>`, and changes to the `withFormik` HOC signature. Developers migrating should consult the official migration guide.
fix
Review the official Formik v1 to v2 migration guide on formik.org to update API calls and component usage. Replace `render` props with child callback functions (e.g., `<Formik>{(formikProps) => ...}</Formik>`). Update `resetForm` to accept a partial next initial state object instead of just initial values.
affects: >=2.0.0
gotchaThe `initialValues` prop in Formik does not automatically reinitialize the form state if the prop changes after the component first mounts. This can lead to forms displaying outdated data if `initialValues` are fetched asynchronously or updated externally.
fix
Set the `enableReinitialize` prop to `true` on the `<Formik>` component or in the `useFormik` hook configuration to instruct Formik to reinitialize the form when `initialValues` change (based on deep equality). For versions prior to 2.4.6, also ensure `initialValues` are not being mutated directly, as a patch in 2.4.6 introduced deep cloning to prevent this.
affects: <2.4.6
gotchaFormik versions prior to 2.4.8 may experience type errors or unexpected behavior when used with React 19 due to changes in React's global `JSX` namespace. Specifically, `JSX.IntrinsicElements` was replaced with `React.JSX.IntrinsicElements`.
fix
Upgrade Formik to version 2.4.8 or newer to ensure full compatibility with React 19. If upgrading is not immediately possible, consider custom type augmentations if working with TypeScript, though upgrading is the recommended solution.
affects: <2.4.8
deprecatedIn Formik v2, the `render` prop for `<Formik>`, `<Field>`, `<FastField>`, and `<FieldArray>` components has been deprecated. While it may still function with a console warning, it is slated for removal in future major versions.
fix
Replace the `render` prop with a child callback function. For example, instead of `<Formik render={props => <MyForm {...props} />} />`, use `<Formik>{(formikProps) => <MyForm {...formikProps} />}</Formik>`.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: Cannot destructure property 'values' of 'formik' as it is undefined.
This error typically occurs when `initialValues` are not provided to the `<Formik>` component or `useFormik` hook, or if they are `null` or `undefined` during the initial render. Formik requires initial values to set up its internal state.
fix
Ensure that `initialValues` are always an object, even if empty, and are consistently available when Formik initializes. For example: `<Formik initialValues={{ email: '', password: '' }} ...>` or `useFormik({ initialValues: { email: '', password: '' }, ... });`
Initial values are not updating when my component re-renders with new props.
By default, Formik only uses `initialValues` to initialize the form state once. Subsequent changes to the `initialValues` prop will not automatically update the form.
fix
Add the `enableReinitialize` prop to your `<Formik>` component or `useFormik` hook configuration: `<Formik enableReinitialize={true} ...>`. This tells Formik to reinitialize the form's state whenever `initialValues` (or `validationSchema` or `initialStatus`) deeply change.
Formik is not a function or Field is not defined when using require().
Formik is predominantly distributed as an ES Module (ESM). Using CommonJS `require()` syntax directly might lead to issues when attempting to import named exports or the default export.
fix
Use ES Module `import` syntax: `import { Formik, Field, useFormik } from 'formik';`. Ensure your project's build setup (e.g., Babel, Webpack, TypeScript) is configured to handle ESM correctly.
TypeError: Cannot read properties of undefined (reading 'name') when using Field or ErrorMessage.
This usually indicates that the `name` prop on a `<Field>` or `<ErrorMessage>` component does not correspond to a key present in the form's `initialValues` object, or the `name` is simply missing.
fix
Verify that every `<Field>` and `<ErrorMessage>` has a `name` prop that exactly matches a key in your `initialValues` object (e.g., `name='email'` corresponds to `{ email: '' }` in `initialValues`). Ensure all nested fields are correctly represented in the `initialValues` structure.
My form doesn't submit, but I don't see any error messages.
If validation fails (either via `validate` function or `validationSchema`), Formik will prevent submission. If there are no `<ErrorMessage>` components or other UI to display these errors, the submission will silently fail.
fix
Ensure all form fields have an associated `<ErrorMessage name="fieldName" />` to display specific validation feedback. For a general error message, you can conditionally render a message based on the `formik.errors` object, for example: `{!formik.isValid && formik.submitCount > 0 && <div style={{color: 'red'}}>Please fix the errors above.</div>}`.
Upgrade
Version history
2.4.9latest on npm
Audit
Dependencies
reactrequiredFormik is a React-specific library and requires React to function. It's listed as a peer dependency.
@types/reactoptionalRequired for TypeScript environments, as Formik ships its own types and relies on React's type definitions. A recent issue highlighted missing peerDependency in strict pnpm modes.
@types/hoist-non-react-staticsrequiredA missing dependency added in Formik 2.4.5 to correctly handle static properties.
Agent activity
2 hits · last 30 days
node
2
Resources
formik — npm install formik · libregistry