javascript - How to get a clear concept of React key property? -


i've been using reactjs when comes "key" property don't know how works.

say in parent component render :

render: function() {    // datalist = [{id: 1}, {id: 2}, {id: 3}];  => initial state   // datalist = [{id: 2}, {id: 3}, {id: 4}];  => second datalist state    var somecomponentlist = [];    this.state.datalist.foreach(function(data) {     somecomponentlist.push(       <somecomponent key={data.id} id={data.id}/>       )   })    return (     <div>       {somecomponentlist}     </div>     ) } 

in somecomponent :

var somecomponent = react.createclass({     render : function({         // render work here     }),     componentwillreceiveprops: function(nextprops) {         console.log(this.props.id == nextprops.id);     } }) 

so in componentwillreceiveprops expect 3 false console result (which if didn't give key attribute <somecomponent>) after setstate() have 1 false because reactjs seems know {id: 2} & {id: 3} identical they're given in different order in datalist state

i found brief documentation on reactjs official :

when react reconciles keyed children, ensure child key reordered (instead of clobbered) or destroyed (instead of reused).

can explain how works?

https://facebook.github.io/react/docs/reconciliation.html#keys

if specify key, react able find insertion, deletion, substitution , moves in o(n) using hash table.

it's simple hash table (of siblings) lookup, , makes react try reuse components have same key.

a rough explanation,
without keys:
[1] [2] [3]
[2] [3] [4]
list-wise diff, [updateattributes x3]
keys:
[1] [2] [3] nil
nil [2] [3] [4]
list of [2] [3] [4], [2] has key matching [2] no changes, [3] has key ... [3] no changes, [4] has no key , no more nodes in original list insert, [1] destroyed