Created
December 7, 2024 18:20
-
-
Save eranbetzalel/edf4ec006f6b09a5fbd0f33a1f1a9791 to your computer and use it in GitHub Desktop.
A lightweight React hook to generate unique keys for items without predefined IDs, avoiding the pitfalls of using array indexes as keys. Perfect for rendering lists where item identities are not explicitly defined.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useState} from 'react'; | |
import {nanoid} from 'nanoid'; | |
export type ItemWithId<T> = T & { id: string }; | |
export const useIdGeneratedItems = <T>(items: T[]): [ItemWithId<T>[], (items: ItemWithId<T>[]) => void] => { | |
const [itemsWithId, setItemsWithId] = useState(() => items.map(item => ({...item, id: nanoid()}))); | |
return [itemsWithId, setItemsWithId]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment