reactjs - Is there a way to get React to autodefine "keys" for children? -


i'm learning react, , stumbled upon quirk "dynamic children."

preamble code example:

// render pass 1 <card>   <p>paragraph 1</p>   <p>paragraph 2</p> </card>  // render pass 2 <card>   <p>paragraph 2</p> </card> 

in second render() pass, seems way vdom diffing works deletes second child, transforms text in first "paragraph 2." it's fast, you'll see weird stuff happening if needed state persist on say... second child!

so react suggests using "key" attribute tags. vdom diffing surprise-free , you'll see state getting preserved across renders().

my question: there way react set "keys" on own rather doing way suggest?

no, there not.

the default behavior of react when there no keys specified use naive approach updating components in-place, observed. functionally, equivalent specifying default key according element's index respect siblings. in example, like:

// render pass 1 <card>   <p key={0}>paragraph 1</p>   <p key={1}>paragraph 2</p> </card>  // render pass 2 <card>   <p key={0}>paragraph 2</p> </card> 

that's why see text first element transformed, note not optimal outcome. why can't react use more intelligent automatic key? answer in order so, there 2 options, , neither ideal:

  1. they make assumptions structure of app. in short example, it's obvious human paragraphs should matched according text content. that's not true in cases, , it's hard extend kind of logic more complex scenarios custom elements, lots of props, nested children, etc.

  2. they use fancy general-purpose diffing algorithm, these can quite costly in terms of performance react conscientious of. react documentation on reconciliation says:

    there many algorithms attempt find minimum sets of operations transform list of elements. levenshtein distance can find minimum using single element insertion, deletion , substitution in o(n2). if use levenshtein, doesn't find when node has moved position , algorithms have worse complexity.

so, either way, benefit of "automatic key assignment" comes set of drawbacks well. in end, it's not worth it, considering in cases assigning keys manually not difficult or cumbersome. further down on same documentation page:

in practice, finding key not hard. of time, element going display has unique id. when that's not case, can add new id property model or hash parts of content generate key. remember key has unique among siblings, not globally unique.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -