Repository navigation
Description
Summary
In [email protected], react-hooks/rules-of-hooks crashes ESLint with an unhandled TypeError when a hook call appears in unreachable top-level code. Inside a component, an unreachable hook after an exhaustive return leaks the enclosing Program code path's segment into the component's analysis and emits a spurious conditional-hook error, even though RulesOfHooks.ts intends to ignore unreachable hooks.
Affected Version
- Published
[email protected](current npmlatest, verified with[email protected]on Node 22.22.2 and Node 24.22.1) main@edae846a9a17442c00429f2b15375afbfa0376c9(RulesOfHooks.ts,code-path-analyzer.js)
Minimal Reproduction
// repro.mjs (npm i [email protected] [email protected])
import { Linter } from 'eslint';
import reactHooks from 'eslint-plugin-react-hooks';
const linter = new Linter({ configType: 'flat' });
const config = [{
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
parserOptions: { ecmaFeatures: { jsx: true } },
},
plugins: { 'react-hooks': reactHooks },
rules: { 'react-hooks/rules-of-hooks': 'error' },
}];
// Case 1: Hard ESLint crash on top-level unreachable hook
try {
linter.verify('throw new Error("fail");\nuseState(0);\n', config);
} catch (err) {
console.error(err);
}
// Case 2: Cross-scope segment leak -> false positive on unreachable hook
console.log(
JSON.stringify(
linter.verify(
'function C({ cond }) {\n if (cond) return null;\n return <div />;\n useState(0);\n}\n',
config,
),
null,
2,
),
);Observed Output ([email protected], [email protected])
Case 1 (crashes ESLint):
TypeError: Cannot read properties of undefined (reading 'reachable')
Occurred while linting <input>:1
Rule: "react-hooks/rules-of-hooks"
at Object.onCodePathEnd (.../node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js:55202:34)
at Object.emit (.../node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js:54823:28)
Case 2 (spurious conditional-hook error):
[
{
"ruleId": "react-hooks/rules-of-hooks",
"severity": 2,
"message": "React Hook \"useState\" is called conditionally. React Hooks must be called in the exact same order in every component render.",
"line": 4,
"column": 3
}
]Expected Behavior
- Case 1: ESLint does not crash, and the unreachable top-level hook is ignored by
rules-of-hooks(matchingRulesOfHooks.ts:556-561, which runs before all diagnostics and leaves unreachable code tono-unreachable). - Case 2: The unreachable hook is ignored by
rules-of-hooks(0 errors).
Root Cause
- In
code-path-analyzer.js:196-217(andleaveFromCurrentSegmentat:231-235), the vendored code-path analyzer emitsonCodePathSegmentStartandonCodePathSegmentEndonly whensegment.reachableistrue(and emits nothing for unreachable segments). - In
RulesOfHooks.ts:292-294,rules-of-hooksmaintains a single flatcodePathSegmentStackacross nested code paths (pushononCodePathSegmentStart,popononCodePathSegmentEnd, ignoring thesegmentargument) and assumeslast(codePathSegmentStack)always points to the active segment of the current code path (CallExpressionat:760-767), relying onif (!segment.reachable) continue;at:559to skip unreachable hooks. - When control flow leaves a reachable segment (via
throw/return) and enters an unreachable segment:onCodePathSegmentEndpops the reachable segment, whileonCodePathSegmentStartis not emitted for the unreachable segment.- At top-level (
Program),codePathSegmentStackbecomes empty, solast(codePathSegmentStack)isundefined.reactHooksMap.set(undefined, ...)storesundefined, andonCodePathEndcrashes atif (!segment.reachable)(RulesOfHooks.ts:559). - Inside a nested component with multiple paths (
if (cond) return null; return <div />;),last(codePathSegmentStack)falls back to the enclosingProgramcode path's still-open reachable segment. That foreign segment has1path from start to end (1n !== 2n), bypassing:559and triggering a false conditional-hook error.
Suggested Fix Direction
Both parts below are required to resolve both failure modes:
- Scope segment tracking per code path: Push a fresh per-code-path collection (e.g. a
Set<Rule.CodePathSegment>usingadd(segment)ononCodePathSegmentStartanddelete(segment)ononCodePathSegmentEnd(segment)) ononCodePathStartand pop it ononCodePathEnd. This prevents cross-code-path segment leaks structurally and avoids assuming strict LIFO exit order, though scoping alone still leaves Case 1 with an emptyProgramsegment set. - Skip recording hook calls in
CallExpressionwhen the current code path has no active reachable segment (!codePathSegment || !codePathSegment.reachable), and defensively guardif (!segment || !segment.reachable) continue;inonCodePathEnd. Checking reachability alone without per-code-path scoping would not fix Case 2 because the leaked outerProgramsegment is reachable.
Together, both changes fix Case 1 and Case 2 while preserving existing diagnostics for conditional hooks and hooks called inside nested callbacks.
Metadata
Metadata
Assignees
Labels
No labels
Activity