Fix Report: ESLint Rules of Hooks Bug in Default Export Arrow Functions #35420
+25
−14
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem Description
A critical bug was identified in the
eslint-plugin-react-hookspackage where the "Rules of Hooks" were not being enforced for React Hooks called within anonymous default export arrow functions.Example of Buggy Behavior
The following code should have triggered an ESLint error but was incorrectly marked as valid:
Root Cause Analysis
The issue resided in the
getFunctionName()utility function withinRulesOfHooks.ts. This function is responsible for determining the name of the function currently being analyzed.ExportDefaultDeclarationas a parent node forArrowFunctionExpressionorFunctionExpression.getFunctionName()returnedundefinedfor these anonymous default exports, the rule's logic fell into a lenientelseblock that skipped reporting unless the code was explicitly determined to be inside another known component or hook.use).Solution
The fix involved two primary changes to
packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts:1. Enhanced Function Name Detection
Updated
getFunctionName()to detect when a function is a default export and return a synthetic identifier with the name"default".2. Robust Error Reporting
Improved the error reporting logic to handle synthetic identifiers. Previously, the code called
getSourceCode().getText(codePathFunctionName), which would throw an error on synthetic nodes that don't exist in the actual source text.Verification Results
Automated Tests
The fix was verified by moving existing "TODO" test cases in
ESLintRulesOfHooks-test.jsfrom thevalidsuite to theinvalidsuite.packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.jsdefaultexport case without affecting the intentional leniency for generic callbacks outside of React contexts.Impact
This fix ensures that developers using anonymous default exports (a common pattern in React) are properly warned when they violate the Rules of Hooks, preventing potential runtime bugs related to hook execution order.