본문 바로가기
React

State lifting은 어떻게, 왜 쓸까?

by 학식러 2024. 2. 8.

State lifting

  • 종종 동일한 데이터에 대한 변경사항을 여러 컴포넌트에 반영해야 할 필요가 있다. 이럴 때는 가장 가까운 공통 조상으로 state를 끌어올리는 것이 좋다.

- React 공식 문서

 

방법

  • 자식 컴포넌트에서 특정 작업을 수행하면 콜백함수를 수행한다.
  • 그 콜백함수 안에는 부모 컴포넌트에서 prop으로 전달한 함수를 실행시킨다.
// GameBoard.jsx 자식 컴포넌트
const handleSelectSquare = (rowIndex, colIndex) => {
  setGameBoard((prevGameBoard) => {
    const updatedBoard = [...prevGameBoard.map(innerArray => [...innerArray])]
    updatedBoard[rowIndex][colIndex] = activePlayerSymbol
    return updatedBoard
  });

  onSelectSquare();
}

<button onClick={() => handleSelectSquare(rowIndex, colIndex)}>{playerSymbol}</button>
// App.jsx 부모 컴포넌트
const [activePlayer, setActivePlayer] = useState('X')

const handleSelectSquare = () => {
  setActivePlayer(curActivePlayer => curActivePlayer === 'X' ? 'O' : 'X')
}

<GameBoard onSelectSquare={handleSelectSquare} activePlayerSymbol={activePlayer} />
  • GameBoard 자식 컴포넌트에서 activePlayer라는 state를 변경시키는 것이 아니라 부모 컴포넌트에서 state를 변경시킬 수 있게 된다.
  • 그리고 이러한 activePlayer state를 다른 자식인 Player에게 prop으로 전달하여 사용할 수 있다.
// App.jsx 부모 컴포넌트
<Player initialName="Player 1" symbol="X" isActive={activePlayer === 'X'} />
<Player initialName="Player 2" symbol="O" isActive={activePlayer === 'O'} />

효과

자식 컴포넌트 내부에서 부모 컴포넌트의 함수를 실행시킬 수 있다.

⇒ 부모 컴포넌트에서 state를 변경시킬 수 있게 됨.

⇒ 공통 부모인 컴포넌트에서 다른 자식에게 동일한 state를 사용할 수 있음.

댓글