React

리액트에서 useState가 불변성을 유지하는 방법

milliwonkim 2023. 3. 28. 19:58
반응형
SMALL

밑의 코드는 useState 소스코드를 간소화해서 useState의 원리를 설명하는 코드입니다.

 

Object.assign을 이용해서 새 객체를 생성해서 state에 할당합니다.

따라서 state의 불변성을 보장합니다.

let currentState; // current state value

function useState(initialState) {
  // set current state to the initial state if it hasn't been set yet
  if (!currentState) {
    currentState = initialState;
  }

  function setState(newState) {
    // create a new state object by merging the current state with the new state
    currentState = Object.assign({}, currentState, newState);

    // trigger a re-render of the component
    renderComponent();
  }

  // return the current state value and the setState function
  return [currentState, setState];
}
반응형
LIST