반응형
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
'React' 카테고리의 다른 글
리액트에서 불변성이 필요한 이유 (0) | 2023.03.27 |
---|---|
React에서 Dropdown을 만들 때, Dropdown 렌더링을 display: none이 좋을까? visibility: hidden이 좋을까? (0) | 2023.03.27 |
React에서 Context API, Redux, Recoil 분해해보기 (0) | 2023.03.27 |
React Hooks는 클로저를 사용하는가? (0) | 2023.03.15 |
리액트의 소스코드를 대략적으로 분석해보자 - 1 (0) | 2023.03.15 |