[React] 無駄 React.Fragment (`<></>`) ない良い

3 min read
hiroweb developer

無駄な<></>は記述しないようにしようという話。

事前知識

無駄な React.Fragment はそのまま出力される

ビルド前

両方とも HTML のレンダリング結果は同じである。

Sample1Sample2
const Sample1 = () => {
  return (
    <>
      <>
        <div>About</div>
      </>
      <>
        <div>About</div>
      </>
    </>
  );
};

無駄な Fragment が記述されたコンポーネント(Sample1)

const Sample2 = () => {
  return (
    <>
      <div>About</div>
      <div>About</div>
    </>
  );
};

Sample1 から無駄な Fragment を取り除いたコンポーネント(Sample2)

ビルド後

HTML のレンダリング結果は同じでも、ビルド後の JavaScript のソースは異なる。ビルドしてもReact.Fragmentは定義した通り出力される。

Sample1Sample2
const Sample1 = () => {
  return /*#__PURE__*/ React.createElement(
    React.Fragment,
    null,
    /*#__PURE__*/ React.createElement(
      React.Fragment,
      null,
      /*#__PURE__*/ React.createElement("div", null, "About")
    ),
    /*#__PURE__*/ React.createElement(
      React.Fragment,
      null,
      /*#__PURE__*/ React.createElement("div", null, "About")
    )
  );
};
const Sample2 = () => {
  return /*#__PURE__*/ React.createElement(
    React.Fragment,
    null,
    /*#__PURE__*/ React.createElement("div", null, "About"),
    /*#__PURE__*/ React.createElement("div", null, "About")
  );
};

変換結果のプレイグラウンド、こちら(Babel - Try it out)に置いておく。

Babelでの変換は上記の通りだが、TypeScriptでの変換もFragmentは同様に残る。

まとめ

記述したReact.Fragmentは最適化されず残ってしまう。大きな副作用があるわけではないので無駄に記述してしまいがちだが、その分ファイルサイズの肥大化やスクリプトの解析時間に影響を与えてしまうため、無駄に記述するのはやめよう。

こういうトップレベルに無駄なReact.Fragmentが残りがちなので気をつけよう。

const Component = () => {
  return (
    <>
      <div className="Component"></div>
    </>
  );
};