use-stable-ids

React hook to generate stable IDs for list items without unique IDs.
Installation
npm install use-stable-ids
Usage
import { useStableIds } from 'use-stable-ids'
const items = [{ name: 'Product 1' }, { name: 'Product 2' }]
const stable = useStableIds(items, {
getKey: item => item.name
})
return (
<>
{stable.map(item => (
<div key={item.__stableId}>{item.name}</div>
))}
</>
)
Options
Option | Type | Default | Description |
---|
getKey | (item) => string | (required) | Unique identifier for each item |
idGenerator | () => string | crypto.randomUUID() or fallback | Custom ID generator |
idFieldName | string | __stableId | Field name to store the stable ID |
License
MIT
🧪 Example
Here is a simple product list using useStableIds
:
const rawProducts = [
{ name: 'Sneakers', price: 120 },
{ name: 'Jacket', price: 250 },
{ name: 'Backpack', price: 80 },
]
const products = useStableIds(rawProducts, {
getKey: (item) => item.name + item.price,
})
return (
<>
{products.map(p => (
<div key={p.__stableId}>
{p.name} - ${p.price}
</div>
))}
</>
)