In React, when rendering a mapping from elements of a list/array/iterable to React elements, we're required to attach a locally-unique key to each element. Generally this is so that if an element changes or is removed, React only needs to rerender that specific element rather than the whole list. This key is required to be a string, and if an element-specific key is not forthcoming, there is an npm package* (shortid) for generating them.
Why did the React designers set this requirement rather than allowing any immutable value? In particular, it makes sense to me to be able to use a Symbol
, which cannot be converted to a unique string. (Upon re-examining my specific case where I wanted to use a Symbol
, I realized it was unnecessary, but the question still stands in general.)
* There also used to be a package specifically designed for this called react-key-index
but it seems to have disappeared from github.
key="Foo"
andkey={Symbol('Foo')}
could represent different items.