Skip to content

[eslint-plugin-react-hooks] rules-of-hooks crashes on top-level unreachable hooks and misreports unreachable hooks inside components #38438

Description

@Tortleya

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

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 (matching RulesOfHooks.ts:556-561, which runs before all diagnostics and leaves unreachable code to no-unreachable).
  • Case 2: The unreachable hook is ignored by rules-of-hooks (0 errors).

Root Cause

  1. In code-path-analyzer.js:196-217 (and leaveFromCurrentSegment at :231-235), the vendored code-path analyzer emits onCodePathSegmentStart and onCodePathSegmentEnd only when segment.reachable is true (and emits nothing for unreachable segments).
  2. In RulesOfHooks.ts:292-294, rules-of-hooks maintains a single flat codePathSegmentStack across nested code paths (push on onCodePathSegmentStart, pop on onCodePathSegmentEnd, ignoring the segment argument) and assumes last(codePathSegmentStack) always points to the active segment of the current code path (CallExpression at :760-767), relying on if (!segment.reachable) continue; at :559 to skip unreachable hooks.
  3. When control flow leaves a reachable segment (via throw/return) and enters an unreachable segment:
    • onCodePathSegmentEnd pops the reachable segment, while onCodePathSegmentStart is not emitted for the unreachable segment.
    • At top-level (Program), codePathSegmentStack becomes empty, so last(codePathSegmentStack) is undefined. reactHooksMap.set(undefined, ...) stores undefined, and onCodePathEnd crashes at if (!segment.reachable) (RulesOfHooks.ts:559).
    • Inside a nested component with multiple paths (if (cond) return null; return <div />;), last(codePathSegmentStack) falls back to the enclosing Program code path's still-open reachable segment. That foreign segment has 1 path from start to end (1n !== 2n), bypassing :559 and triggering a false conditional-hook error.

Suggested Fix Direction

Both parts below are required to resolve both failure modes:

  1. Scope segment tracking per code path: Push a fresh per-code-path collection (e.g. a Set<Rule.CodePathSegment> using add(segment) on onCodePathSegmentStart and delete(segment) on onCodePathSegmentEnd(segment)) on onCodePathStart and pop it on onCodePathEnd. This prevents cross-code-path segment leaks structurally and avoids assuming strict LIFO exit order, though scoping alone still leaves Case 1 with an empty Program segment set.
  2. Skip recording hook calls in CallExpression when the current code path has no active reachable segment (!codePathSegment || !codePathSegment.reachable), and defensively guard if (!segment || !segment.reachable) continue; in onCodePathEnd. Checking reachability alone without per-code-path scoping would not fix Case 2 because the leaked outer Program segment is reachable.

Together, both changes fix Case 1 and Case 2 while preserving existing diagnostics for conditional hooks and hooks called inside nested callbacks.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions