Skip to content

Instantly share code, notes, and snippets.

@eranbetzalel
Created December 7, 2024 18:20
Show Gist options
  • Save eranbetzalel/edf4ec006f6b09a5fbd0f33a1f1a9791 to your computer and use it in GitHub Desktop.
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.
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