Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. # React Keys
  2.  
  3. Consider the difference between these:
  4.  
  5. ```typescript
  6. function NameList({names}) {
  7. return (<ul>{names.map((name, index) =>
  8. <li key={index}>{name}</li>
  9. )}</ul>);
  10. }
  11. ```
  12.  
  13. Given these names
  14.  
  15. ```typescript
  16. <NameList names={['Bob', 'Charles']} />
  17. ```
  18.  
  19. It would render
  20. ```html
  21. <ul>
  22. <li key="0"><Bob/li>
  23. <li key="1"><Charles/li>
  24. </ul>
  25. ```
  26.  
  27. If it re-renders with the names
  28.  
  29. ```typescript
  30. <NameList names={['Alfred', 'Bob', 'Charles']} />
  31. ```
  32.  
  33. It would cause the following changes:
  34. ```diff
  35. <ul>
  36. - <li key="0"><Bob/li>
  37. - <li key="1"><Charles/li>
  38. + <li key="0">Alfred</li>
  39. + <li key="1">Bob</li>
  40. + <li key="2"><Charles/li>
  41. </ul>
  42. ```
  43.  
  44. Since the index `key` wasn't stable, as far as React is concerned, the two first `<li>` have changed, and a third one was added.
  45.  
  46. However, if you use `name` as the `key`
  47. ```diff
  48. function NameList({names}) {
  49. return (<ul>{names.map((name, index) =>
  50. - <li key={index}>{name}</li>
  51. + <li key={name}>{name}</li>
  52. )}</ul>);
  53. }
  54. ```
  55.  
  56. The same scenario would result in a much smaller change:
  57. ```diff
  58. <ul>
  59. + <li key="Alfred">Alfred</li>
  60. <li key="Bob"><Bob/li>
  61. <li key="Charles"><Charles/li>
  62. </ul>
  63. ```
  64.  
  65. Here, React can figure out that the two original `<li>` haven't changed, but a third one was prepended, so it just adds that.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement