Skip to content

Bug: eslint-plugin-react-hooks rules-of-hooks misses hook usage in class properties with typescript-eslint v5+ parser #27431

@ecraig12345

Description

@ecraig12345

React version: any version with hooks
eslint-plugin-react-hooks version: 4.6.0 / all (still repros in 5.0.0-canary-f81c0f1ed-20230927)

Steps To Reproduce

Link to code example: https://github.com/ecraig12345/repro-react-hooks-eslint

  1. Install dependencies:
    • eslint-plugin-react-hooks (any version)
    • @typescript-eslint/parser v5 or greater
    • eslint v6 or greater
    • typescript (any version)
  2. In the project's eslint config, set the parser to @typescript-eslint/parser and enable the react-hooks/rules-of-hooks rule
{
  parser: '@typescript-eslint/parser',
  plugins: ['react-hooks'],
  rules: {
    'react-hooks/rules-of-hooks': 'error',
  }
}
  1. Add some code that calls a hook inside a class property function (not a class method)
import { useState } from 'react';
class Test {
  useHook = () => {
    useState();
  }
}
  1. Run eslint on the project

The current behavior

No errors are flagged.

The expected behavior

One error is flagged.

The behavior was correct with @typescript-eslint/parser v4 (as demonstrated in the full repro).

Root cause

In @typescript-eslint/parser v5, the AST node type ClassProperty was renamed to PropertyDefinition. The rules-of-hooks rule needs to be updated to check for this additional type.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions