Recently I've started reading react hooks code and I see this.
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
The dispatcher is an object that initialized by resolveDispatcher().
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
if (!(dispatcher !== null)) {
{
throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component..." );
}
}
return dispatcher;
}
and ReactCurrentDispatcher is a object with one property that called current
.
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
now my question is how and where react handles the logic of hooks? where is the logic of useImperativeHandle or ...?
CodePudding user response:
In general, to answer questions like this I clone the repo and use ag
or git grep
:
(react) $ git grep useImperativeHandle
[...]
packages/react-reconciler/src/ReactFiberHooks.new.js: useImperativeHandle<T>(
[...]
That leads me to these mappings right here – the code for useImperativeHandle
, for example, seems to be these three functions.
Understanding how they work and interact with the React fiber system is another rabbit hole.