<aside> 💡 모던 리액트 Deep Dive의 3장을 읽고 정리한 내용입니다.
</aside>
import { useState } from 'react'
const [state, setState] = useState(initialState)
함수형 컴포넌트 내부에서 상태를 정의하고, 관리할 수 있게 해주는 훅
리액트의 렌더링과 상태
export default function App() {
const [,setState] = useState(0)
let state = 'hello'
function handleButtonClick() {
state = 'hi'
setState()
}
return (
<main>
<h1>{state}</h1>
<button onClick={handleButtonClick}>hi</button>
</main>
)
}
useState의 내부 구현 생각해보기
const MyReact = function(){
const global = {}
let index = 0
function useState(initialState) {
// 애플리케이션 최초 접근 시, 전체 states 배열 초기화
if (!global.states) {
global.states = []
}
// state: 현재 상태값 확인, 없으면 초깃값 설정
const currentState = global.states[index] || initialState
global.states[index = currentState
// setter: index를 기억하는 즉시실행함수
const setState = (function () {
let currentIndex = index
return function (value) {
// 상태 업데이트
global.states[currentIndex] = value
// 이후 컴포넌트 렌더..
}
})()
}
// 각 state마다 새로운 index 할당
index += 1
return [currentState, setState]
}
게으른 초기화(lazy initialization)
const [count, setCount] = useState(() =>
Number.parseInt(window.localStorage.getItem(cacheKey)))
useState(함수)
localStorage
, sessionStorage
에 대한 접근, 배열에 대한 접근(map
, filter
, find
), 초깃값 계산을 위해 함수 호출이 필요한 경우 useEffect(() => {
}, [props, state])