TutorialsCourses
Course Menu
Formik for Beginners

The useField Hook

Intro

The Field component pre-dates the release of hooks. Hooks help remove much of the complexity and helps integrate Formik into more complex scenarios. You are able to create a new component, and get access to all the values you need without wrapping stuff in a Field component. This allows for next level composition that hooks opened up.

Removing Field

First off lets remove the field param and remove Field which was passed MySpecialField that it used to render. So now we just have a basic looking input with a className.

const MySpecialField = () => {
  return <input className="border-2" />;
};

Transition to useField

Now rather receiving field from a wrapping Field we pass our name prop which is firstName into the useField hook. This hook is exported from formik like so import { useField } from "formik"

const MySpecialField = () => {
  const [field] = useField("firstName");

  return <input {...field} className="border-2" />;
};

The field that is returned is identical to the field that was returned from Field so all you need to do is spread it on like before.

With our special field our code is now just 2 lines, and a regular React component. There are no more children as functions and no need to remember all the different ways that Field can render.

import React from "react";
import { Formik, Form, useField } from "formik";

const MySpecialField = () => {
  const [field] = useField("firstName");

  return <input {...field} className="border-2" />;
};

function App() {
  const handleSubmit = (values) => {
    console.log(values);
  };

  return (
    <div className="App">
      <Formik
        initialValues={{
          firstName: "",
        }}
        onSubmit={handleSubmit}
      >
        {() => {
          return (
            <Form className="h-screen flex content-center flex-col justify-center">
              <div className="space-x-4 flex content-center justify-center">
                <MySpecialField />
                <button
                  type="submit"
                  className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                >
                  Submit
                </button>
              </div>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}

export default App;