Formik - useFormikContext and useField hooks

As I’m using Formik to build forms inside React applications below there are some patterns you may enjoy.


Let’s say that you have a form build using formik:

import React, { FunctionComponent } from "react";
import { Formik, FieldProps, Field } from "formik";

type FormValues = {
  name: string;
  email: string;

const UserForm: React.FunctionComponent = () => {
  return (
      initalValues={{ name: "", email: "" }}
      onSubmit={(values) => sendDataToAPI(values)}
      {(props) => (
        <form onSubmit={props.onSubmit}>
          <Field name="name">
            {({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}
          <Field name="email">
            {({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}

const CustomInput: React.FunctionComponent<JSX.IntrinsicElements["input"]> = ({
}) => <input {...props} />;


I want to start with useField. Previously to create a field in formik you have to first create a Field component and then pass children render prop:

import { FieldProps, Field } from "formik";

<Field name="name">
  {({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}

In 2.0.0 version maintainers introduced a new hook useField. It can be use to abstract that Field underneath is CustomInput:

import React, { FunctionComponent } from "react";
import { useField } from "formik";

const FormikCustomInput: React.FunctionComponent<{ name: string }> = ({
}) => {
  const [field] = useField(name);
  return <CustomInput {...field} />;

And then use it inside UserForm:

<form onSubmit={props.onSubmit}>
  <FormikCustomInput name="name" />
  <FormikCustomInput name="email" />

Where you can use it? In a place where you have multiple forms that use the same Fields.


Another addition is useFormikContext. This is a Formik hook to get formikBag (formik values, errors and helpers) in your component. In previous versions you had to use connect to get your component into Formik context. Thanks to this new hook - there is no need for that. Where it can be useful? Inside nested forms when you don’t want to have prop drilling problem.


Formik added two new hooks: useField and useFormikContext to ease creating reusable and nested forms. Be sure to check them out!