useState源码解读
-
react方法主入口==>react/packages/react/index.js
export {
...
useState,
...
} from './src/ReactClient'; -
前往/src/ReactClient
import {
...,
useState,
...
} from './ReactHooks'; -
前往/ReactHooks
export function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}-
resolveDispatcher
function resolveDispatcher() {
const dispatcher = ReactSharedInternals.H;
...
return ((dispatcher: any): Dispatcher);
}
-
-
前往/react/packages/shared/ReactSharedInternals.js
import * as React from 'react';
const ReactSharedInternals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
export default ReactSharedInternals; -
前往/node_modules/@types/react/index.d.ts
/**
* Returns a stateful value, and a function to update it.
*
* @version 16.8.0
* @see {@link https://react.dev/reference/react/useState}
*/
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
// convenience overload when first argument is omitted
/**
* Returns a stateful value, and a function to update it.
*
* @version 16.8.0
* @see {@link https://react.dev/reference/react/useState}
*/
function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>]; -
前往/react/packages/react-reconciler/src/ReactFiberHooks.js
const HooksDispatcherOnMount: Dispatcher = {
...,
useState: mountState,
...,
};-
mountState
function mountState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
const hook = mountStateImpl(initialState);
const queue = hook.queue;
const dispatch: Dispatch<BasicStateAction<S>> = (dispatchSetState.bind(
null,
currentlyRenderingFiber,
queue,
): any);
queue.dispatch = dispatch;
return [hook.memoizedState, dispatch];
}-
mountStateImpl
function mountStateImpl<S>(initialState: (() => S) | S): Hook {
const hook = mountWorkInProgressHook();
if (typeof initialState === 'function') {
const initialStateInitializer = initialState;
// $FlowFixMe[incompatible-use]: Flow doesn't like mixed types
initialState = initialStateInitializer();
if (shouldDoubleInvokeUserFnsInHooksDEV) {
setIsStrictModeForDevtools(true);
// $FlowFixMe[incompatible-use]: Flow doesn't like mixed types
initialStateInitializer();
setIsStrictModeForDevtools(false);
}
}
hook.memoizedState = hook.baseState = initialState;
const queue: UpdateQueue<S, BasicStateAction<S>> = {
pending: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: (initialState: any),
};
hook.queue = queue;
return hook;
}
-
-