1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React Hook Form】useFormとuseFormContextの使い分け

Last updated at Posted at 2024-12-15

はじめに

業務でReact Hook Formを使用している際に、useFormuseFormContextの2つの違いについて疑問を感じたため、整理して記事にしました。名前が似ているため混乱しやすいですが、それぞれの使い方には違いがあります。

この記事は個人的なアウトプットを目的として作成したものです。そのため、誤った情報や不足している内容が含まれている可能性があります。もし間違いや気になる点がございましたら、ぜひご指摘いただけますと幸いです

useFormuseFormContextについて

useFormとは

useFormは、フォームを簡単に管理するためのカスタム フックです。オプションの引数として 1 つのオブジェクトを受け取ります。

  • 役割:useFormフォームの状態の管理
  • 使い所:単一のフォームを管理する場合

useFormContextとは

このカスタム フックを使用すると、フォーム コンテキストにアクセスできます。useFormContextこれは、コンテキストをプロパティとして渡すことが不便になるような、深くネストされた構造で使用することを目的としています。

  • 役割:useFormContextは作成済みのフォーム状態をContextを通じて取得する
  • 使い所:ネストされたコンポーネントでフォーム状態にアクセスする場合

使いわけ

useFormを使う場合

useFormはフォームの状態管理を行う基本的なフックです。単一のフォームを管理する場合はuseFormだけで十分です。

import { useForm } from "react-hook-form";

const Form = () => {
  const { register, handleSubmit, reset } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name")} />
      <button type="submit">Submit</button>
    </form>
  );
};

useFormContextを使う場合

useFormContextは、FormProviderで提供されたフォームの状態にアクセスするためのフックです。フォームが複数のコンポーネントで構成されていたり、フォーム状態を共有する必要がある場合に使用します。

import { useForm, FormProvider, useFormContext } from "react-hook-form";

const InputField = ({ name }) => {
  const { register } = useFormContext(); // useFormContextでフォーム状態にアクセス
  return <input {...register(name)} />;
};

const MyForm = () => {
  const methods = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <InputField name="firstName" />
        <InputField name="lastName" />
        <button type="submit">Submit</button>
      </form>
    </FormProvider>
  );
};

終わりに

useFormuseFormContextは名前が似ているものの、それぞれ異なる役割を持っています。この違いを意識することで、React Hook Formをより効率的に活用できるようしていきたいです。

参考

『react-hook-formのuseFormとuseFormContextの違い』Qiita

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?