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.FC と React.VFC を使わなくなった理由

1
Posted at

はじめに

React の TypeScript プロジェクトで、以前は React.FC(Function Component)や React.VFC(Void Function Component)を使ってコンポーネントの型を定義することが一般的でした。しかし、現在ではこれらの使用が推奨されなくなりました。その理由を明確に理解するために記事にまとめました。

問題点1: children が自動的に含まれてしまう

React.FC を使用すると、children プロパティが自動的に型に含まれてしまいます。これにより、意図しない API になってしまうことがあります。

悪い例(React.FC を使用)

import React from 'react';

type Props = {
  title: string;
};

// children を受け取らないコンポーネントのつもり
const Header: React.FC<Props> = ({ title }) => {
  return <h1>{title}</h1>;
};

// しかし、children を渡してもエラーにならない!
<Header title="タイトル">これは本来エラーになるべき</Header>

良い例(関数の引数に型を直接指定)

type Props = {
  title: string;
};

const Header = ({ title }: Props) => {
  return <h1>{title}</h1>;
};

// children を渡すとエラーになる(期待通り)
<Header title="タイトル">これはエラーになる</Header>

問題点2: defaultProps との相性が悪い

React.FCdefaultProps を組み合わせると、型推論が正しく機能しない場合があります。

悪い例

import React from 'react';

type Props = {
  name: string;
  age?: number;
};

const UserProfile: React.FC<Props> = ({ name, age }) => {
  return <div>{name} ({age})</div>;
};

UserProfile.defaultProps = {
  age: 0,
};

// age が undefined の可能性がある(型推論が不正確)

良い例

type Props = {
  name: string;
  age?: number;
};

const UserProfile = ({ name, age = 0 }: Props) => {
  return <div>{name} ({age})</div>;
};

// age は常に number として推論される

問題点3: 型が過剰に複雑になる

React.FCchildrenpropTypesdefaultProps など、古い React API を含む型定義になっています。シンプルな関数コンポーネントには不要な複雑さかなって思います。

推奨される書き方

現在のベストプラクティスは、関数の引数に直接 Props の型を指定することだと思います。

// children が必要な場合
type Props = {
  color: string;
  fontSize: string;
  children: React.ReactNode;
};

const Text = ({ color, fontSize, children }: Props) => {
  return <p style={{ color, fontSize }}>{children}</p>;
};

// children が不要な場合
type UserProps = {
  user: User;
};

const UserProfile = ({ user }: UserProps) => {
  return (
    <dl>
      <dt>名前</dt>
      <dd>{user.name}</dd>
    </dl>
  );
};

まとめ

React.FCReact.VFC を使わない理由は以下の通りです:

  1. children が自動的に含まれる - 意図しない API になる
  2. defaultProps との相性が悪い - 型推論が正しく機能しない
  3. 型が過剰に複雑 - シンプルな関数コンポーネントには不要

現在は、関数の引数に直接 Props の型を指定する方法が推奨されています。これにより、より明確で意図が伝わりやすいコードになります。

おわりに

今回改めて、Reactのchildrenプロップについて復習しましたがやっぱり苦手です…
苦手な原因は、何が入ってくるか得体が知れないからと
改めて感じました。
しかし、今回改めて一つずつ落ち着いて考えることで少し理解が深まったと思います!!

今後も技術にまつわることを沢山書くのでお楽しみに〜

1
0
2

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?