Gelio / tslint-react-hooks

TSLint rule for detecting invalid uses of React Hooks
MIT License
218 stars 10 forks source link

Allow using hooks in React component decorators (like `React.memo`) #4

Closed Gelio closed 5 years ago

Gelio commented 5 years ago

Fixes #2

I added an exception that allows using hooks in function expressions passed to React.memo and React.forwardRef. As far as I know, these are all React top-level APIs that should allow hooks.

Implementation details

Whenever a parent of a hook call is a function expression (either an anonymous function or an arrow function), the rule checks whether the parent of that function expression is a call expression to forwardRef or memo (possibly prefixed by React.).

I noticed that same React. prefix has to be handled when detecting whether a call expression is a React hook, becuase a native React hook can be called by either useState or React.useState.

I came up with a function (isReactApiExpression) that allows for easy matching identifiers that could be prefixed by the React identifier.