{"id":13199,"library":"formik","title":"Formik - React Forms Made Easy","description":"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.","status":"active","version":"2.4.9","language":"javascript","source_language":"en","source_url":"https://github.com/jaredpalmer/formik","tags":["javascript","formik","form","forms","react","react-dom","hooks","react hooks","validation","typescript"],"install":[{"cmd":"npm install formik","lang":"bash","label":"npm"},{"cmd":"yarn add formik","lang":"bash","label":"yarn"},{"cmd":"pnpm add formik","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Formik is a React-specific library and requires React to function. It's listed as a peer dependency.","package":"react","optional":false},{"reason":"Required 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.","package":"@types/react","optional":true},{"reason":"A missing dependency added in Formik 2.4.5 to correctly handle static properties.","package":"@types/hoist-non-react-statics","optional":false}],"imports":[{"note":"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.","wrong":"const Formik = require('formik');","symbol":"Formik","correct":"import { Formik } from 'formik';"},{"note":"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.","wrong":"import Formik from 'formik'; // then Formik.useFormik","symbol":"useFormik","correct":"import { useFormik } from 'formik';"},{"note":"`Field` is a component used for connecting form inputs to Formik state and is a named export. Ensure it's imported directly.","wrong":"const Field = Formik.Field;","symbol":"Field","correct":"import { Field } from 'formik';"},{"note":"`ErrorMessage` is a utility component for displaying validation messages for a given field.","symbol":"ErrorMessage","correct":"import { ErrorMessage } from 'formik';"}],"quickstart":{"code":"import React from 'react';\nimport { useFormik, Form, Field, ErrorMessage } from 'formik';\nimport * as Yup from 'yup'; // Often used for schema validation\n\nconst SignupForm = () => {\n  const formik = useFormik({\n    initialValues: {\n      firstName: '',\n      lastName: '',\n      email: '',\n    },\n    validationSchema: Yup.object({\n      firstName: Yup.string()\n        .max(15, 'Must be 15 characters or less')\n        .required('Required'),\n      lastName: Yup.string()\n        .max(20, 'Must be 20 characters or less')\n        .required('Required'),\n      email: Yup.string().email('Invalid email address').required('Required'),\n    }),\n    onSubmit: async (values, { setSubmitting, resetForm }) => {\n      // Simulate an async submission\n      console.log('Submitting values:', values);\n      await new Promise(resolve => setTimeout(resolve, 500));\n      alert(JSON.stringify(values, null, 2));\n      setSubmitting(false);\n      // Optionally reset the form after submission\n      // resetForm();\n    },\n  });\n\n  return (\n    <Form onSubmit={formik.handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '10px', maxWidth: '300px', margin: '20px auto', padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>\n      <label htmlFor=\"firstName\">First Name</label>\n      <Field\n        id=\"firstName\"\n        name=\"firstName\"\n        type=\"text\"\n        onChange={formik.handleChange}\n        onBlur={formik.handleBlur}\n        value={formik.values.firstName}\n        style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }}\n      />\n      <ErrorMessage name=\"firstName\" component=\"div\" style={{ color: 'red', fontSize: '0.8em' }} />\n\n      <label htmlFor=\"lastName\">Last Name</label>\n      <Field\n        id=\"lastName\"\n        name=\"lastName\"\n        type=\"text\"\n        onChange={formik.handleChange}\n        onBlur={formik.handleBlur}\n        value={formik.values.lastName}\n        style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }}\n      />\n      <ErrorMessage name=\"lastName\" component=\"div\" style={{ color: 'red', fontSize: '0.8em' }} />\n\n      <label htmlFor=\"email\">Email Address</label>\n      <Field\n        id=\"email\"\n        name=\"email\"\n        type=\"email\"\n        onChange={formik.handleChange}\n        onBlur={formik.handleBlur}\n        value={formik.values.email}\n        style={{ padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }}\n      />\n      <ErrorMessage name=\"email\" component=\"div\" style={{ color: 'red', fontSize: '0.8em' }} />\n\n      <button type=\"submit\" disabled={formik.isSubmitting}\n        style={{ padding: '10px 15px', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>\n        Submit\n      </button>\n    </Form>\n  );\n};\n\nexport default SignupForm;","lang":"typescript","description":"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`."},"warnings":[{"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.","message":"Formik 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.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":"<2.4.6"},{"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.","message":"Formik 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`.","severity":"gotcha","affected_versions":"<2.4.8"},{"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>`.","message":"In 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.","severity":"deprecated","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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: '' }, ... });`","cause":"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.","error":"TypeError: Cannot destructure property 'values' of 'formik' as it is undefined."},{"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.","cause":"By default, Formik only uses `initialValues` to initialize the form state once. Subsequent changes to the `initialValues` prop will not automatically update the form.","error":"Initial values are not updating when my component re-renders with new props."},{"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.","cause":"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.","error":"Formik is not a function or Field is not defined when using require()."},{"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.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'name') when using Field or ErrorMessage."},{"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>}`.","cause":"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.","error":"My form doesn't submit, but I don't see any error messages."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}