iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🖍️

Extracting Form Concerns into Custom Hooks in React

に公開
2022/11/09
1件

About This Article

When actually using forms, you often implement them alongside a validation library.

I previously posted in this article that using ReactHookForm (hereafter RHF) is a good way to suppress re-renders.
https://zenn.dev/ishiyama/articles/99aff84e95ef27

In this article, we will create a practical form using RHF and "Zod," a type-safe validation library.
RHF and Zod can be easily combined using the following resolver.

import { zodResolver } from "@hookform/resolvers/zod"

However, even if you implement it straightforwardly, all concerns will be crammed into a single component, likely resulting in a "fat component."
In this article, we will extract the concerns of form processing into custom hooks and create pluggable hooks.

Screen

We are implementing a form screen like the following.

InputField Component

This is the InputField component used hereafter.
Basically, it just wraps the input tag and lists the contents if there are errors, so you can skip this part if you just want to keep reading.

InputField.tsx
export type InputFieldProps = Omit<JSX.IntrinsicElements["input"], "ref"> & {
  errors?: string[]
  inputRef?: React.Ref<HTMLInputElement>
}

export const InputField = (props: InputFieldProps) => {
  const { errors, inputRef, ...others } = props
  return (
    <div>
      <input {...others} ref={inputRef} />
      {errors?.map((x) => (
        <p>
          <small>{x}</small>
        </p>
      ))}
    </div>
  )
}

Implementation Using ReactHookForm and Zod (Straightforward Implementation)

We will implement the form-related processing in a single index.tsx.

$ tree page1
page1
└── index.tsx

It's long, so scanning it is fine.

index.tsx
import { zodResolver } from "@hookform/resolvers/zod"
import {
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
  UseFormRegisterReturn,
} from "react-hook-form"
import { z } from "zod"
import { InputField } from "../../../components/InputField"

const schema = z.object({
  name: z.string().min(5),
  email: z.string().email(),
})
type FormData = z.infer<typeof schema>
const defaultValues: FormData = { name: "", email: "" } as const

const Page = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    mode: "onChange",
    resolver: zodResolver(schema),
    defaultValues,
  })

  const handleValid: SubmitHandler<FormData> = (data, event) => alert("OK")
  const handleInvalid: SubmitErrorHandler<FormData> = (errors, event) =>
    alert("INVALID")

  return (
    <form onSubmit={handleSubmit(handleValid, handleInvalid)} noValidate>
      <div>Name:</div>
      <InputField
        {...convert(register("name"))}
        errors={resolve(errors.name)}
      />
      <div>Email:</div>
      <InputField
        {...convert(register("email"))}
        errors={resolve(errors.email)}
      />
      <button>submit</button>
    </form>
  )
}

// InputField.tsx defines inputRef instead of ref, so we re-set ref to inputRef.
function convert({ ref, ...others }: UseFormRegisterReturn) {
  return { inputRef: ref, ...others }
}

function resolve(field?: { message?: string }) {
  return field?.message ? [field?.message] : undefined
}

export default Page

Even at this point, the visibility is poor, but in reality, much more processing will be included, so further deterioration in readability is expected from here on.

Separating Concerns with Custom Hooks

Extract the form-related processing into useUserForm.ts.
By doing this, I believe the clarity of the Page component has improved.

$ tree page2
page2
├── hooks
│   └── useUserForm.ts
└── index.tsx
index.tsx
import { InputField } from "../../../components/InputField"
import {
  SubmitErrorHandler,
  SubmitHandler,
  UserForm,
  useUserForm,
} from "./hooks/useUserForm"

const Page = () => {
  const { handleSubmit, errors, fieldValues }: UserForm = useUserForm()

  const handleValid: SubmitHandler = (data, event) => alert("OK")
  const handleInvalid: SubmitErrorHandler = (errors, event) => alert("INVALID")

  return (
    <form onSubmit={handleSubmit(handleValid, handleInvalid)} noValidate>
      <div>Name:</div>
      <InputField {...fieldValues.name} errors={errors.name} />
      <div>Email:</div>
      <InputField {...fieldValues.email} errors={errors.email} />
      <button>submit</button>
    </form>
  )
}

export default Page

The key point is that instead of depending on the "implementation" of useUserForm, we are implementing it in a way that depends on the UserForm type.
By doing so, as long as the constraints of UserForm are followed, the implementation of the Page component itself is not affected.

*Note: UserForm is the ReturnType of useUserForm() exported in hooks/useUserForm.ts.

For those who have business with the form processing, please modify this custom hook.

hooks/useUserForm.ts
import { zodResolver } from "@hookform/resolvers/zod"
import {
  SubmitErrorHandler as SubmitErrorHandlerOriginal,
  SubmitHandler as SubmitHandlerOriginal,
  useForm,
  UseFormRegisterReturn,
} from "react-hook-form"
import { z } from "zod"

const schema = z.object({
  name: z.string().min(5),
  email: z.string().email(),
})
type FormValues = z.infer<typeof schema>
const defaultValues: FormValues = { name: "", email: "" } as const

export type UserForm = ReturnType<typeof useUserForm>
export type SubmitHandler = SubmitHandlerOriginal<FormValues>
export type SubmitErrorHandler = SubmitErrorHandlerOriginal<FormValues>

export const useUserForm = () => {
  const {
    register,
    handleSubmit: handleSubmitOriginal,
    formState: { errors },
  } = useForm({
    mode: "onChange",
    resolver: zodResolver(schema),
    defaultValues,
  })

  const handleSubmit = (
    onValid: SubmitHandler,
    onInvalid: SubmitErrorHandler
  ) => handleSubmitOriginal(onValid, onInvalid)

  return {
    handleSubmit,
    errors: {
      name: resolve(errors.name),
      email: resolve(errors.email),
    },
    fieldValues: {
      name: convert(register("name")),
      email: convert(register("email")),
    },
  }
}

// InputField.tsx defines inputRef instead of ref, so we re-set ref to inputRef.
function convert({ ref, ...others }: UseFormRegisterReturn) {
  return { inputRef: ref, ...others }
}

function resolve(field?: { message?: string }) {
  return field?.message ? [field?.message] : undefined
}

hooks/useUserForm.ts does not need to be checked for modifications unrelated to the form, making it easier to add "other processes."

Switching to a Mock Custom Hook

In the early stages of project development or when performing unit tests, there are times when you want to replace processing so that it behaves in a way that is convenient for you.
As long as it follows the constraints of UserForm, form processing can easily be switched to a mock object.

$ tree page3
page3
├── hooks
│   ├── useUserForm.ts
│   └── useUserFormMock.ts // Switch to this
└── index.tsx

Create a custom hook that suits your needs, following the UserForm definition.

hooks/useUserFormMock.ts
import { UserForm } from "./useUserForm"

                               // ⭐
export const useUserForm = (): UserForm => {
  const handleSubmit = (onValid: any) => () => {
    onValid()
    return Promise.resolve()
  }

  return {
    handleSubmit,
    errors: {
      name: undefined,
      email: undefined,
    },
    fieldValues: {
      name: { ...mockFieldValue, name: "name" },
      email: { ...mockFieldValue, name: "email" },
    },
  }
}

const mockFieldValue = {
  name: "mock",
  onChange: () => Promise.resolve(),
  onBlur: () => Promise.resolve(),
  inputRef: () => {},
}

Finally, replace the implementation of UserForm with useUserFormMock.

index.ts
import { InputField } from "../../../components/InputField"
import {
  SubmitErrorHandler,
  SubmitHandler,
-  useUserForm,
  UserForm,
} from "./hooks/useUserForm"
+ import { useUserForm } from "./hooks/useUserFormMock"

const Page = () => {
  const { handleSubmit, errors, fieldValues }: UserForm = useUserForm()

  const handleValid: SubmitHandler = (data, event) => alert("OK")
  const handleInvalid: SubmitErrorHandler = (errors, event) => alert("INVALID")

  return (
    <form onSubmit={handleSubmit(handleValid, handleInvalid)} noValidate>
      <div>Name:</div>
      <InputField {...fieldValues.name} errors={errors.name} />
      <div>Email:</div>
      <InputField {...fieldValues.email} errors={errors.email} />
      <button>submit</button>
    </form>
  )
}

export default Page

In this way, the success processing (the convenient Mock processing) is executed regardless of the input value.

Source

The code used is stored here.

https://github.com/ishiyama0530/react-form-recipes/tree/main/src/pages/advanced

Summary

We have successfully extracted the concerns related to form processing into a custom hook.
The Page component does not import Zod or RHF; it encapsulates those implementations within useUserForm.
Therefore, even if you were to switch the validation library from Zod to yup, the modification would be complete just by changing useUserForm, as long as you do not change the exported constraints.
This is the strength of pluggable components and why they are resilient to change.

In large-scale systems, you might define interfaces to further increase independence, use DI containers, and manage dependencies at a higher level of the application.
Additionally, since things might be managed in an aggregation layer (like a BFF), you may not always require this level of abstraction on the frontend.
It is best to perform an appropriate design after understanding the scale of your system.

Discussion