본문 바로가기
프로그래머로의 여정

JS에서 key는 무엇인가

by nunaaa 2025. 9. 4.

아래 코드에서 key는 무엇인가요?

이 코드에서는 key가 명시적으로 존재하지 않습니다.

현재 코드 분석

const items = ['a', 'b', 'c', 'd'];

const result = items.map(function(currentValue, index, array) {
  return {
    value: currentValue,
    position: index,
    total: array.length,
    isFirst: index === 0,
    isLast: index === array.length - 1
  };
});

console.log(result);

이 코드는 순수 JavaScript로, React 컴포넌트가 아닙니다. 따라서 React의 key 속성 개념이 적용되지 않습니다.

React에서 사용하려면 key 추가 필요

React 컴포넌트로 변환 시

function ItemList() {
  const items = ['a', 'b', 'c', 'd'];

  return (
    <div>
      {items.map(function(currentValue, index, array) {
        const itemData = {
          value: currentValue,
          position: index,
          total: array.length,
          isFirst: index === 0,
          isLast: index === array.length - 1
        };

        return (
          <div key={currentValue + index}> {/* ✅ key 추가 필요 */}
            {JSON.stringify(itemData)}
          </div>
        );
      })}
    </div>
  );
}

더 나은 key 사용법

function ItemList() {
  const items = ['a', 'b', 'c', 'd'];

  return (
    <div>
      {items.map((currentValue, index, array) => (
        <ItemComponent
          key={`item-${index}-${currentValue}`} // ✅ 고유한 key
          value={currentValue}
          index={index}
          total={array.length}
          isFirst={index === 0}
          isLast={index === array.length - 1}
        />
      ))}
    </div>
  );
}

function ItemComponent({ value, index, total, isFirst, isLast }) {
  return (
    <div className="item">
      <p>값: {value}</p>
      <p>위치: {index + 1}/{total}</p>
      <p>{isFirst && '첫 번째 항목'}</p>
      <p>{isLast && '마지막 항목'}</p>
    </div>
  );
}

key가 필요한 시점 vs 필요없는 시점

✅ key가 필요한 경우

// React JSX 내에서 배열을 렌더링할 때
{items.map(item => (
  <div key={item.id}>{item.name}</div>
))}

❌ key가 필요없는 경우

// 순수 JavaScript 배열 변환
const newArray = items.map(item => item.toUpperCase());

// 데이터 처리만 하는 경우
const processedData = items.map((item, index) => ({
  item,
  index,
  processed: true
}));

원본 코드의 결과

원본 코드의 실행 결과는 다음과 같습니다:

[
  { value: 'a', position: 0, total: 4, isFirst: true, isLast: false },
  { value: 'b', position: 1, total: 4, isFirst: false, isLast: false },
  { value: 'c', position: 2, total: 4, isFirst: false, isLast: false },
  { value: 'd', position: 3, total: 4, isFirst: false, isLast: true }
]

이 코드는 단순히 JavaScript 객체를 생성할 뿐, React 요소를 생성하지 않기 때문에 key 속성이 필요하지 않습니다.

결론

key는 React의 Virtual DOM 개념에서만 필요합니다:

  • 순수 JavaScript 배열 조작: key ❌ 필요없음
  • React JSX 내 배열 렌더링: key ✅ 필수

따라서 이 코드에서는 key가 존재하지 않으며, 필요하지도 않습니다. 이 코드를 React 컴포넌트에서 사용하려면 JSX를 반환할 때 key를 추가해야 합니다.