[React] What does it mean to give a component a key?

React component key, I had put it on somehow, so I sorted it out.

目次

Meaning of assigning a Key.

React components are given keys in this way.
Here, the key is given when the KeyValuePair object is turned in a map.

<GridLayout>
  {props.historyList.map(d => {
    return (
      <Item href={`/history/${d.history_tag_key}`} key={d.history_tag_key} className='GridItem'>
        <ItemTitle>{d.history_tag}</ItemTitle>
      </Item>
    )
  })}
</GridLayout>

Here, if you do not give a key to the component, you will get an error in eslint.

<GridLayout>
  {props.historyList.map(d => {
    return (
      <Item href={`/history/${d.history_tag_key}`} className='GridItem'>
        <ItemTitle>{d.history_tag}</ItemTitle>
      </Item>
    )
  })}
</GridLayout>

KEY attribute, you are told to put on.

Missing "key" prop for element in iterator

Simply by assigning a key that is unique, the eslint error is eliminated, though,
The reason for assigning a key here is to manage the rendering of the component.

The component is redrawn at the timing when the key is changed in accordance with the update of the object being turned in the map.
For this reason, a unique value should be assigned to key, but to manage rendering, indexes and random values should be avoided as much as possible.

Resetting the state of a component by changing the key.

When the state was managed by a component, the state was not reset after a page transition.
This can be handled with useEffect.

For example, if you want to change the state every time the userId is changed, you can use useEffect.

export default function ProfilePage({ userId }) {
  const [comment, setComment] = useState('');

  // Avoid: Resetting state on prop change in an Effect
  useEffect(() => {
    setComment('');
  }, [userId]);
  // ...
}

However, this is inefficient, as the ProfilePage and its child components are first rendered with the stale values and then rendered again.

The key attribute is used here.
The key attribute is given when the component is called.

export default function ProfilePage({ userId }) {
  return (
    <Profile
      userId={userId}
      key={userId}
    />
  );
}

function Profile({ userId }) {
  // This and any other state below will reset on key change automatically
  const [comment, setComment] = useState('');
  // ...
}

This way, the React DOM is recreated every time the key is changed. In other words, it resets the state in the component, so every time the userId changes, the internal state is reset.

For more detailed information, please see the official description.
https://ja.react.dev/learn/you-might-not-need-an-effect#resetting-all-state-when-a-prop-changes

Summary

eslintのメッセージに沿ってkeyをつけてましたが、Reactの公式を読むと、よりレンダリングへの知識が深まります。

よかったらシェアしてね!
目次