key-defender
v1.0.1-alpha.0
Published
Manage keys in React/Vue applications.
Downloads
2
Readme
key-defender
What and Why and How it works
In React and Vue applications when you don't have stable IDs for list items, you may use index as a key for identification, but there will be issues when it comes to components with state. Here is a React official post for an in-depth explanation on the negative impacts of using an index as a key.
It is recommended to use an ID or email or something unique as a key for each item, but sometimes, we just don't have it. Of course we can generate some unique IDs, meanwhile your data schema will be changed.
What if we manage all keys somewhere else, like in a Map which uses list item (i.e. an object) as a key?
How to use
npm install --save key-defender
// some React Component
import k from 'key-defender';
// ...
<ul>
{list.map(item => (
<Row key={k(item)} title={item.title} />
))}
</ul>;
// ...
Caveats
You should always use an object as a parameter in key-defender, for only objects are unique regardless of their values are equal or not, so we can tell a difference in a Map.
'abcd' === 'abcd' // true
{ title: 'abcd' } === { title: 'abcd' } // false
If you are handling a list with basic typed values, decorate it before using key-defender.
['foo', 'foo', 'bar', 'bar'][('foo', 'foo', 'bar', 'bar')] // origin list
.map(_ => ({ val: _ })); // decorated list