hook由react包中导出
export const useState: Dispatcher['useState'] = (initialState) => {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
};
核心由resolveDispatcher();提供 这块读取currentDispatcher.current
const currentDispatcher: { current: Dispatcher | null } = {
current: null
};
export const resolveDispatcher = (): Dispatcher => {
const dispatcher = currentDispatcher.current;
if (dispatcher === null) {
throw new Error('hook 只能在函数组件中执行');
}
return dispatcher;
};
export default currentDispatcher;
而这个currentDispatcher也会在renderHook中被赋值 核心由current来判断两个hook状态 一个是mount时一个是更新时的
if (current !== null) {
//update
currentDispatcher.current = HooksDispatcherOnUpdate;
} else {
//mount
currentDispatcher.current = HooksDispatcherOnMount;
}
const HooksDispatcherOnMount: Dispatcher = {
useState: mountState,
useEffect: mountEffect,
useTransition: mountTransition,
useRef: mountRef,
useContext: readContext,
use,
useMemo: mountMemo,
useCallback: mountCallback
};
const HooksDispatcherOnUpdate: Dispatcher = {
useState: updateState,
useEffect: updateEffect,
useTransition: updateTransition,
useRef: updateRef,
useContext: readContext,
use,
useMemo: updateMemo,
useCallback: updateCallback
};
所以可以看出来核心的实现还是在react-reconcile里 就这样建立起来了hook和react包以及react-recolier的