Hooks Implementation
Relevant source files
The following files were used as context for generating this wiki page:- packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts
- packages/react-debug-tools/src/tests/ReactHooksInspection-test.js
- packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js
- packages/react-reconciler/src/tests/ReactHooks-test.internal.js
- packages/react-devtools-shared/src/hooks/tests/parseHookNames-test.js
- packages/react-debug-tools/src/tests/ReactDevToolsHooksIntegration-test.js
- packages/react-reconciler/README.md
The React Hooks implementation provides state and other React features to function components. The system is designed with a core reconciler logic, a public-facing API, and extensive developer tooling for linting and debugging. This separation allows the core hook mechanism to be renderer-agnostic, while providing a consistent and robust developer experience.
The implementation relies on a "dispatcher" pattern, where the React.useState, React.useEffect, etc. calls are delegated to the currently active renderer's implementation. This is managed through ReactCurrentDispatcher. During rendering, the reconciler provides a specific dispatcher that interacts with the component's fiber to manage state and effects. This architecture is complemented by static analysis tools like eslint-plugin-react-hooks to enforce the Rules of Hooks and by React DevTools for runtime inspection and debugging.
Hooks Inspection and Debugging
The react-debug-tools package provides the core functionality for inspecting the state and structure of hooks within a component. This is fundamental for React DevTools to display information about hooks.
Hook Inspection Tree
The inspectHooks and inspectHooksOfFiber functions from react-debug-tools traverse the linked list of hooks associated with a fiber and generate a tree structure representing the custom and built-in hooks.
Each node in the tree contains key information about the hook:
| Property | Description |
|---|---|
id | The index of the hook in the fiber's list. null for custom hooks. |
name | The name of the hook (e.g., State, Effect, Custom). |
value | The current value of the hook (e.g., state value, or useDebugValue output for custom hooks). |
subHooks | An array of hooks called within a custom hook. |
isStateEditable | A boolean indicating if the hook's state (like useState or useReducer) can be modified from DevTools. |
hookSource | An object containing the source file name, line, and column number where the hook is defined. |
Sources: packages/react-debug-tools/src/tests/ReactHooksInspection-test.js:13-23, packages/react-debug-tools/src/tests/ReactHooksInspection-test.js:42-69
The following diagram illustrates the process of inspecting a component's hooks.
This diagram shows how DevTools uses react-debug-tools to get a structured representation of a component's hooks from the fiber managed by the reconciler.
Sources: packages/react-debug-tools/src/tests/ReactDevToolsHooksIntegration-test.js:49-55, packages/react-debug-tools/src/tests/ReactHooksInspection-test.js:33-36
Overriding Hook State
React DevTools allows for direct manipulation of stateful hooks (useState, useReducer). The overrideHookState function, injected by the DevTools global hook, enables this functionality. When a developer edits a state value in DevTools, this function is called with the target fiber, the hook's ID, the path to the value (for nested state), and the new value. This triggers a re-render of the component with the updated state.
Sources: packages/react-debug-tools/src/tests/ReactDevToolsHooksIntegration-test.js:81-84, packages/react-debug-tools/src/tests/ReactDevToolsHooksIntegration-test.js:122-125
Parsing Hook Names for DevTools
To improve the debugging experience, React DevTools can display the variable names assigned to stateful hooks (e.g., const [count, setCount] = useState(0) shows up as "State (count)"). This is a complex process that involves fetching source code and source maps, and then parsing them to find the hook declarations.
The overall flow is:
- Flatten Hooks List: Get a flat list of all named hooks from the component's hooks tree. Unnamed hooks like
useEffectare skipped. - Load Source and Metadata: For each unique source location, fetch the runtime source code.
- Extract and Load Source Map: Search the source code for a
sourceMappingURL. If found, load and parse the source map (either inline Base64 or an external file). - Parse Source and Metadata: This CPU-intensive task runs in a Web Worker. It uses the source maps to find the original source code and then parses it with an AST parser (like Babel) to extract the variable names associated with hook calls.
Sources: packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js:25-50, packages/react-devtools-shared/src/hooks/tests/parseHookNames-test.js:68-81
The following diagram illustrates this process.
This flowchart shows the pipeline for parsing hook names, from inspecting the component to displaying the names in DevTools, highlighting the split between the UI thread and a worker thread for performance.
Sources: packages/react-devtools-shared/src/hooks/tests/parseHookNames-test.js:71-79, packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js:103-111
Extended Source Maps
To optimize this process and avoid full AST parsing, React supports extended source map formats (x_facebook_sources or x_react_sources). These source maps contain pre-calculated metadata about hook names, which can be decoded directly without parsing the original source code. This provides a significant performance improvement.
Sources: packages/react-devtools-shared/src/hooks/tests/parseHookNames-test.js:501-514
Enforcing the Rules of Hooks
The eslint-plugin-react-hooks package is crucial for ensuring hooks are used correctly and safely. It enforces two main rules:
- Only call hooks at the top level of a function component or custom hook.
- Only call hooks from React function components or custom hooks.
rules-of-hooks Implementation
The rules-of-hooks lint rule uses a CodePathAnalyzer to traverse the code paths within a function. It identifies calls to hooks and validates their position.
The core logic is as follows:
- Identify Hooks and Components: It determines if a function is a component (starts with an uppercase letter) or a hook (starts with "use").
- Analyze Code Paths: For each function, it analyzes all possible execution paths.
- Validate Hook Calls: It checks if hook calls (
useState,useEffect, etc.) are present on all possible code paths. If a hook is called conditionally (e.g., inside anifstatement or a loop), it violates the rules. - Report Violations: If a hook is called conditionally, in a loop, in a nested function, or outside of a valid component/hook, it reports an ESLint error.
Sources: packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:25-36, packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:314-335
The following diagram shows the simplified logic for the rules-of-hooks linter.
This diagram outlines the decision-making process of the ESLint rule to ensure hooks are called unconditionally at the top level.
Sources: packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:20-23, packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:314-335
A key function is isHook, which uses a regex ^use[A-Z0-9] to identify functions that are hooks by their name.
Sources: packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:20-23
Bailing Out of Renders
React includes an optimization to bail out of the render phase if a component's state and props have not changed. For function components with hooks, React compares the new state from a useState or useReducer update with the current state. If all state values are the same (using Object.is for comparison) and the component's props have not changed (for React.memo components), the render can be aborted early.
This optimization can sometimes happen without even entering the component's render function if React determines the update queue is empty and the new state is identical to the old one. However, if context has changed, the component will never bail out, as it must re-render to receive the new context value.
Sources: packages/react-reconciler/src/tests/ReactHooks-test.internal.js:49-70, packages/react-reconciler/src/tests/ReactHooks-test.internal.js:203-228