Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # React Keys
- Consider the difference between these:
- ```typescript
- function NameList({names}) {
- return (<ul>{names.map((name, index) =>
- <li key={index}>{name}</li>
- )}</ul>);
- }
- ```
- Given these names
- ```typescript
- <NameList names={['Bob', 'Charles']} />
- ```
- It would render
- ```html
- <ul>
- <li key="0"><Bob/li>
- <li key="1"><Charles/li>
- </ul>
- ```
- If it re-renders with the names
- ```typescript
- <NameList names={['Alfred', 'Bob', 'Charles']} />
- ```
- It would cause the following changes:
- ```diff
- <ul>
- - <li key="0"><Bob/li>
- - <li key="1"><Charles/li>
- + <li key="0">Alfred</li>
- + <li key="1">Bob</li>
- + <li key="2"><Charles/li>
- </ul>
- ```
- 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.
- However, if you use `name` as the `key`
- ```diff
- function NameList({names}) {
- return (<ul>{names.map((name, index) =>
- - <li key={index}>{name}</li>
- + <li key={name}>{name}</li>
- )}</ul>);
- }
- ```
- The same scenario would result in a much smaller change:
- ```diff
- <ul>
- + <li key="Alfred">Alfred</li>
- <li key="Bob"><Bob/li>
- <li key="Charles"><Charles/li>
- </ul>
- ```
- 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