Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 2.24 KB

2016-01-02-keys-in-children-components-are-important.md

File metadata and controls

48 lines (37 loc) · 2.24 KB
layout title tip-number tip-username tip-username-profile tip-tldr tip-writer-support redirect_from categories
post
Keys in children components are important
2
loverajoel
The key is an attribute that you must pass to all components created dynamically from an array. It's a unique and constant id that React uses to identify each component in the DOM and to know whether it's a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.
/en/keys-in-children-components-are-important/
en
react

The key is an attribute that you must pass to all components created dynamically from an array. It's a unique and constant id that React uses to identify each component in the DOM and to know whether it's a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.

Key is not really about performance, it's more about identity (which in turn leads to better performance). Randomly assigned and changing values do not form an identity Paul O’Shannessy

  • Use an existing unique value of the object.
  • Define the keys in the parent components, not in child components
//bad
...
render() {
	<div key={% raw %}{{item.key}}{% endraw %}>{% raw %}{{item.name}}{% endraw %}</div>
}
...

//good
<MyComponent key={% raw %}{{item.key}}{% endraw %}/>
//bad
<MyComponent key={% raw %}{{Math.random()}}{% endraw %}/>