import { useState } from "react";
const [state, setState] = useState(initialState);
function Component() {
let state = "hello";
function handleButtonClick() {
state = "hi";
}
return (
<>
<h1>{state}</h1>
<button onClick={handleButtonClick}>hi</button>
</>
);
}
이유: 리렌더링을 발생시키기 위한 조건을 전혀 충족하지 못하고 있기 때문
렌더링이 일어나게끔 변경한 코드
function Component() {
const [, triggerRender] = useState();
let state = "hello";
function handleButtonClick() {
state = "hi";
triggerRender();
}
return (
<>
<h1>{state}</h1>
<button onClick={handleButtonClick}>hi</button>
</>
);
}
실제 코드는 아님. 실제 코드는 useReducer를 사용해 구현돼 있음
const MyReact = function () {
const global = {};
let index = 0;
function useState(initialState) {
if (!global.states) {
global.states = [];
}
const currentState = global.states[index] || initialState;
global.states[index] = currentState;
const setState = (function () {
// 현재 index를 클로저로 가둬놔서 이후에도 계속해서 동일한 index에 접근할 수 있도록 함
let currentIndex = index;
return function (value) {
global.states[currentIndex] = value;
};
})();
index = index + 1;
return [currentState, setState];
}
// 실제 useState를 사용하는 컴포넌트
function Component() {
const [value, setValue] = useState(0);
// ...
}
};
// 바로 값을 집어넣음
const [count, setCount] = useState(
Number.parseInt(window.localStorage.getItem(cacheKey))
);
// 함수를 실행해 값을 반환 -> 게으른 초기화
const [count, setCount] = useState(() =>
Number.parseInt(window.localStorage.getItem(cacheKey))
);
⭐️ 사용 권장되는 경우
useState의 초기값이 복잡하거나 무거운 연산을 포함하는 등 실행 비용이 많이 드는 경우
Number.parseInt(window.localStorage.getItem(cacheKey))
와 같이 한 번 실행되는 데 어느 정도 비용이 드는 값