How unique should a React component Key be?

This is a quick one: what is the scope in which the children keys have to be unique? Is this just the parent component or the whole app?

If the latter is true, does it mean react diff algorithm will preserve an element when its moved across parent components?

Unique within its siblings, so the level directly under its parent. The children of the parent component however can use the same key again, because finally, react will compose the complete key out of the key of the current component and all of its ancestors. The example below only contains auto-generated keys, but if you provide your own key, it will be used instead.

React ID's

You can see the composed ID’s in Chrome developer tools (tab Elements).

Yes, looks like it…if you re-parent it, it’ll give a different reactid (eg. )

and will unmount/re-mount again. …

,componentWillUnmount: function() {
 //console.log("unmounted:", this.props);
,componentDidMount: function(){
  // console.log("mounted:", this.props);
  this.state.intervalId = setInterval(this.incrementCount, 1000);
 this.state.timeoutId = setTimeout(this.setColorToBlack, 300);

So, better not to store state in the view component itself, since it might reset itself. The above fiddle is just a demo to prove a point.

Other related links:
Using keys to identify nested components in React.js

I did wish React had something to consider scoped/nested key states beyond the same level, but i guess the performance of unmounting/re-mounting again should hopefully not be too detrimental.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Prevent a webpage from navigating away using JavaScript

Similar Posts