Reputation: 5132
I was going through the tutorial of React here: https://www.tutorialspoint.com/reactjs/reactjs_components.htm
In this page, there is a example, where author says, how passing key prop in the component helps in improving performance in re-rendering. Can someone explain how?
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"id":1,
"name":"Foo",
"age":"20"
},
{
"id":2,
"name":"Bar",
"age":"30"
},
{
"id":3,
"name":"Baz",
"age":"40"
}
]
}
}
render() {
return (
<div>
<Header/>
<table>
<tbody>
{this.state.data.map((person, i) => <TableRow key = {i}
data = {person} />)}
</tbody>
</table>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td>{this.props.data.name}</td>
<td>{this.props.data.age}</td>
</tr>
);
}
}
export default App;
Upvotes: 2
Views: 45
Reputation: 890
You may be interested in reading about how reconciliation functions in react. The linked article eventually discusses keys as a solution to the problem of react-dom rendering scaling to the order of O(n^3) where n is the number of elements in the dom.
React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in then subsequent tree.
Keys allow the react-dom to not have to mutate the data in the dom. If the entire dom-tree is rebuilt, it is computationally less scalar. With keys, react can use a better algorithm:
React implements a heuristic O(n) algorithm based on two assumptions:
- Two elements of different types will produce different trees.
- The developer can hint at which child elements may be stable across different renders with a key prop.
If you read over the linked article, this should make a lot more sense.
Upvotes: 0
Reputation: 202618
Yes, key
is a special prop/attribute in react. When mapping JSX react will actually complain if you do not specify keys, or have any duplicate keys.
Keys help React identify which items have changed, are added, or are removed.
If the key is the same as the last render react won't re-render that piece. This is also one of the gotchas when devs use the index parameter of the array::map
function as the key... if one of the elements actually is different, but has the same key as the previous render, react won't re-render it. You should ensure the keys you use are unique within your dataset.
https://reactjs.org/docs/lists-and-keys.html
Upvotes: 1