Fix: Prevent false positives in rules-of-hooks for regular classesFix: Prevent false positives in rules-of-hooks for regular classes
Description
This PR fixes #35264 by preventing false positives in the react-hooks/rules-of-hooks ESLint rule when hooks are used inside regular class instances (not React components).
Problem
The ESLint rule was incorrectly flagging hooks used in ANY class method as invalid, assuming all classes are React components. This caused false positives for regular classes that don't extend React.Component.
Example of false positive:
class Store {
use() {
return React.useState(4); // Was incorrectly flagged as error
}
}
Solution
Added a helper function isReactComponentClass() that checks if a class actually extends React.Component or React.PureComponent before reporting an error. Regular classes (without extends or extending other classes) can now use hooks in their methods without triggering false positives.
Changes
- Added
isReactComponentClass()helper function inRulesOfHooks.ts - Updated the class method check to only flag hooks in actual React component classes
- Added test cases for both valid (regular classes) and invalid (React component classes) scenarios
Testing
- Added test case for regular class with hooks (should be valid)
- Added test cases for React component classes with hooks (should be invalid)
- Existing tests continue to passThe ESLint rule 'react-hooks/rules-of-hooks' was incorrectly flagging hooks used in regular class methods as invalid, assuming all classes are React components.
This fix adds a helper function isReactComponentClass() that checks if a class actually extends React.Component or React.PureComponent before reporting an error. Regular classes (without extends) can now use hooks in their methods without triggering false positives.
Fixes #35264
Summary
How did you test this change?
Hi @hukshh!
Thank you for your pull request and welcome to our community.
Action Required
In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.
Process
In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.
Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.
If you have received this in error or have any questions, please contact us at [email protected]. Thanks!
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!