nishimura.clubnishimura.club

React の List 表示のために緩くユニークなIDを作成する

作成日
2021-12-24
更新日
2022-08-03

React で list 表示をする際には、keyを設定し、その値で rendering の挙動を変えています。

useState で配列が頻繁に変更される場合に、index を使用する場合 rendeing の挙動がおかしくなります。そのため各要素に緩いユニークを付与します。

const createId = (): string => { const tmpId: string = new Date().getTime().toString(16) return `list-${tmpId}` } createId()

リストと key – React

処理が重複する可能性ある場合は、uuidを使う

例)チャット

import { v4 as uuid } from 'uuid' uuid()

Related