var key = require('weak-key'); const todos = [{ text: 'write module' }, { text: 'writes tests' }, { text: 'publish' }]; todos.map(key); // ['weak-key-0', 'weak-key-1', 'weak-key-2']; todos.reverse().map(key); // ['weak-key-2', 'weak-key-1', 'weak-key-0']; [{}, {}].map(key); // ['weak-key-3', 'weak-key-4'];
This only works on things that typeof thing === 'object' so you can't use it on primitive types (numbers, strings, ...)
which makes it great to use for React's key={}
import key from 'weak-key'; export default function Todo({ items }) { return ( <ul> { items.map(item => <li key={key(item)}>{item.text}</li> ) } </ul> ); }