[240102] react/no-array-index-key 린트 규칙 해결
react/no-array-index-key 린트 규칙 해결
{rows.map((row, rowIdx) => (
<TableRow
key={`${row}-${rowIdx}`}
>))}
- 이번에 회사에서 lint 규칙 변경했는데, 아래와 같은 오류 발생
Do not use Array index in keyseslint [react/no-array-index-key](https://github.com/jsx-eslint/eslint-plugin-react/tree/master/docs/rules/no-array-index-key.md)
(parameter) row: string[]
- 무슨 오류인가? index 값을 쓰지 말라는 규칙임
- index 값을 쓰면 리렌더링 할 때 문제가 된다.
- 그러면 고유한 uuid 값 넣어주면 어떨까 했는데, 해당 방법도 좋은 해결책이 아님
- 왜냐? 매번 리렌더링 될 때 새로운 고유한 값을 넣어주면 key 값을 넣는 이유가 없음 최적화에 별로다.
-
아래 블로그에선 index를 key 로 쓰면 안되는 이유 예시를 잘 보여줌 [React] 배열의 index를 key로 쓰면 안되는 이유
- 스택오버플로우 논쟁 참고
How to create unique keys for React elements?
lint 옵션
- lint 옵션은 순서가 중요하다. (css와 비슷하게 생각하면 됨)
{
"extends": [
"airbnb",
"airbnb-typescript",
"airbnb/hooks",
"plugin:@typescript-eslint/recommended",
"plugin:storybook/recommended",
"next/core-web-vitals",
"plugin:react/jsx-runtime",
"plugin:prettier/recommended"
]
}
Leave a comment