본문 바로가기
Coding Study/Javascript 내장함수

Array.prototype.with()

by bell_one 2026. 1. 15.

MDN 스타일 요약 with() 메서드는 특정 인덱스의 값을 주어진 값으로 교체한 새로운 배열을 반환합니다. 기존의 array[index] = value 방식은 원본 배열을 직접 수정(Mutation)하지만, with()는 원본을 보존합니다. 이는 React에서 state를 변경할 때 복사본을 만들어야 하는 번거로움(Spread 연산자 사용 등)을 획기적으로 줄여줍니다.


React 실무 예시 React에서 체크리스트의 특정 항목만 수정하거나, 리스트 중 하나를 선택해 업데이트할 때 코드가 매우 간결해집니다.

import React, { useState } from 'react';

const TodoList = () => {
  const [todos, setTodos] = useState(["리액트 공부", "운동하기", "독서하기"]);

  const updateTodo = (index) => {
    // 기존 방식: [...todos.slice(0, index), "완료!", ...todos.slice(index + 1)]
    // 혹은: const newTodos = [...todos]; newTodos[index] = "완료!";
    
    // 최신 방식: .with() 한 줄로 해결 (원본 todos는 변하지 않음)
    const newTodos = todos.with(index, "✅ " + todos[index]);
    setTodos(newTodos);
  };

  return (
    <div className="p-5">
      <h3 className="font-bold mb-4">오늘의 할 일 (클릭 시 완료)</h3>
      <ul className="space-y-2">
        {todos.map((todo, i) => (
          <li 
            key={i} 
            onClick={() => updateTodo(i)}
            className="cursor-pointer p-2 bg-gray-100 hover:bg-blue-100 rounded transition"
          >
            {todo}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TodoList;

 

실무 활용 포인트:

  • 불변성(Immutability) 유지: React의 useState에서 배열의 특정 요소만 바꿀 때 [...prev] 같은 복사 과정 없이 바로 새 배열을 만들 수 있어 안전하고 깔끔합니다.
  • 체이닝 가능: 새로운 배열을 반환하기 때문에 const result = arr.with(1, 'A').map(...) 처럼 다른 배열 함수와 이어서 사용할 수 있습니다.
  • 가독성: 코드를 읽는 사람이 "아, 이 위치의 값을 바꾼 새 배열을 만드는구나"라고 즉시 의도를 파악할 수 있습니다.

'Coding Study > Javascript 내장함수' 카테고리의 다른 글

structuredClone()  (0) 2026.01.15
Array.prototype.findLast()  (0) 2026.01.15
Array.prototype.at()  (0) 2026.01.15
Object.fromEntries()  (0) 2026.01.09
Object.values()  (0) 2026.01.08