- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: jsx-react/list-component-no-index
Language: JavaScript
Severity: Warning
Category: Code Style
In JavaScript, particularly when using libraries like React, it’s common to map over arrays and create components for each item. The key
prop is necessary for React’s diffing algorithm to identify each component uniquely. Using array indexes as keys in list components is a bad practice because it can lead to unpredictable behavior.
This is especially true when the list can change dynamically (items added, removed, or reordered), as React uses the keys to determine which items have changed, are added, or are removed. Using indexes as keys can lead to bugs and performance degradation because the index does not uniquely identify the data item; it only reflects the item’s position in the array.
To avoid this, use unique and stable identifiers from your data as keys whenever possible. If your data items have an id
field, for example, you should use that for the key. This ensures that the key remains consistent across different renders, helping React maintain and update the component state correctly. For instance, user.id
is used as a key in the compliant code sample provided.
function UserList(props) {
return (
<ul>
{props.users.map((user, index) => (
<li key={index}>
{user.name} - {user.email}
</li>
))}
</ul>
);
}
function UserList(props) {
return (
<ul>
{props.users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
);
}
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products