ReasonJun

React : JSX key 본문

Frontend/React

React : JSX key

ReasonJun 2023. 6. 12. 12:51
728x90

JSX key is a special attribute used in React.js when rendering lists of elements. When rendering multiple elements or components in a loop, React requires each item to have a unique "key" prop. The key prop helps React keep track of the individual items in the list and efficiently update and reorder them when necessary.

 

The key prop should be assigned a unique identifier for each item in the list. It can be a string or a number, typically sourced from a unique identifier associated with each item in the data set. It's important to note that the key should be stable and not change across re-rendering of the list. Using stable keys allows React to optimize the rendering process and provide better performance.

 

React uses the keys to determine the identity of each element in the list. When the list is re-rendered, React compares the keys of the new elements with the keys of the previous elements. It can then determine which elements were added, removed, or changed, and update only the necessary parts of the DOM.

 

Here's an example of JSX code that demonstrates the usage of keys:

const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' }
];

function MyListComponent() {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

In the code above, we have an array of items, each containing an id and a name. When rendering the list using the map function, we assign the id of each item as the key prop for the corresponding li element. This way, React can keep track of each item individually and efficiently update the list when needed.

 

It's important to choose a unique and stable identifier for the key prop. In most cases, using a unique identifier from the data set (like an ID) is a good practice. Avoid using the array index as the key, especially when the list can be reordered, as it can cause issues with component reordering and performance.

 

A key value is required to apply only the changed part to the actual DOM using the virtual DOM.

 

In the case of a list, when data is accumulated in order, only the last added part is automatically updated in the dom. However, if an element is added in the middle or at the beginning, the scope of the changed part becomes excessively wide. First, when a new element comes in, the entire element is redrawn. Therefore, it is necessary to help the dom recognize only the changed part by entering the key value.

728x90

'Frontend > React' 카테고리의 다른 글

React : useEffect (Hook)  (0) 2023.06.13
React : react developer tools (Chrome Extension)  (0) 2023.06.13
React : HOCs (Higher-Order Components)  (0) 2023.06.12
React : Hooks  (0) 2023.06.12
React : Conditional render  (0) 2023.06.11
Comments