이전 useState-1에 이어서 2는 소스코드를 기반으로 deep-dive를 해보려고 함
아직 나도 살펴보기 전이지만 어디까지 들어갈 수 있는지 한번 보자 ㄱㅈㅇ
→←↑↓
📌⚠️

해당 파일에 들어가면 ↓ 코드와 같은 진입점을 찾을 수 있다.
export function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
Type
useState<S>는initialState를 Parameter로 받고
상태값S와 상태를 갱신하는 함수setState를[S, Dispatch]형태로 리턴
initialState는 값 그 자체이거나() => S형태의lazy initializer함수일 수 있다.
useState함수의 내부의 dispatcher는resolveDispatcher()의 반환한 객체dispatcher.useState(initialState)를 반환하고 있다. function resolveDispatcher() {
const dispatcher = ReactSharedInternals.H;
if (__DEV__) {
if (dispatcher === null) {
console.error(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
}
}
// Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return ((dispatcher: any): Dispatcher);
}
ReactSharedInternals.H를 찾으러 가보자
export type SharedStateClient = {
H: null | Dispatcher, // Hook 관련 정보를 주입할 곳, Type : null or Dispatcher
A: null | AsyncDispatcher,
T: null | BatchConfigTransition
S: null | ((BatchConfigTransition, mixed) => void)
const ReactSharedInternals: SharedStateClient = ({
H: null,
A: null,
T: null,
S: null,
}: any);