0
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】HTML上でmapを使うときにはkey属性を使おう!

Last updated at Posted at 2025-05-15

参考サイト様

公式
https://ja.react.dev/learn/rendering-lists

参考にさせていただいたサイト様
https://watasuke.net/blog/article/react-component-include-key/

アンチパターンなコード

次のようなコードがあります。

{testlist.map((dataid) => (
        <div>
            <p>{dataid[0]}</p>
            <p>{dataid[1]}</p>
        </div>
    ))}
</div>

これは、testlistという配列や辞書(イテレーター)をmapで取り出して動的に同じようなhtmlを生成しています。
divタグがイテレーションの数だけ作られるわけですが、testlist内部の値が変更された場合、DOM側からはその値に対応するdivタグを一意に判断する方法がありません。
そのため、再レンダリングする場合には全体を探索して変更する必要があるのでレンダリング曽速度が遅くなる場合があります。

ベストプラクティス

タグにkeyを指定するのがベストプラクティスとなります。 ただし、keyはmapの値に対応する『ユニーク』な値である必要があります。
{testlist.map((dataid) => (
        <div key={`${dataid[0]}-${dataid[1]}`}>
            <p>{dataid[0]}</p>
            <p>{dataid[1]}</p>
        </div>
    ))}

dataid[0],dataid[1]の組み合わせは一意であるとします。
上のようにdivタグに重複しないkeyを付与することでtestlistの値が変わった場合、変わった箇所に対応するdivタグに一発で辿り着けます。

DOM側はこのkeyをトレースしてくれるので変更箇所のみを再レンダリングするという最適化を行ってくれる訳です。

0
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
0
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?