DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

Formik - useFormikContext and useField hooks

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

Form

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 (
    <Formik<FormValues>
      initalValues={{ name: '', email: '' }}
      onSubmit={(values) => sendDataToAPI(values)}
    >
      {(props) => (
        <form onSubmit={props.onSubmit}>
          <Field name="name">
            {({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}
          </Field>
          <Field name="email">
            {({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}
          </Field>
        </form>
      )}
    </Formik>
  );
};

const CustomInput: React.FunctionComponent<JSX.IntrinsicElements['input']> = ({ ...props }) => (
  <input {...props} />
);
Enter fullscreen mode Exit fullscreen mode

useField

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

import { FieldProps, Field } from 'formik';

<Field name="name">{({ field }: FieldProps<FormValues>) => <CustomInput {...field} />}</Field>;
Enter fullscreen mode Exit fullscreen mode

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

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

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

And then use it inside UserForm:

<form onSubmit={props.onSubmit}>
  <FormikCustomInput name="name" />
  <FormikCustomInput name="email" />
</form>
Enter fullscreen mode Exit fullscreen mode

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

useFormikContext

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 Formikcontext. Thanks to this new hook - there is no need for that. Where it can be useful? Inside nestedforms when you don’t want to have prop drilling problem.

Summary

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

Top comments (0)