Rule reports false positive for anonymous component returned from a function
realyze opened this issue Β· comments
const createMyComponent = () => {
return () => {
const [myState] = React.useState(() => 42);
return <>something</>
};
};
reports a tslint error but the hook is actually used in the root scope.
(Thanks a lot for your work on this project!)
Similar issue when using HOCs.
const MyComponent = withHoc()(() => {
const [state] = useState();
return <>{state}</>;
});
Not sure how to guard against that. For now I just disable rule for the false positive lines.
Yep also running into this with react-intl
's injectIntl
-HOC.
I also got this when trying to define a HOC
const withHoc = <TProps extends object>(Component: ComponentType<TProps>) => (props: TProps) => {
const [state] = useState();
return <Component {...props} />;
};
A hook cannot be used inside of another function
Heuristic used
It is relatively difficult to determine whether a function is a component, a hook, both of which could contain hook calls, or a regular function that should not contain any hook calls. Functions that start with an uppercase letter are always treated as components. From what I'm seeing in eslint-plugin-react-hooks
, they also use a similar heuristic.
If anyone has an idea on how to improve this heuristic, please let me know π
Workaround
A workaround, for now, is to use named function expressions:
const withHoc = <TProps extends object>(Component: ComponentType<TProps>) =>
function WrappedComponent(props: TProps) { // Notice that the component has a name
const [state] = useState();
return <Component {...props} />;
};
Although, I noticed that due to a bug, a named function expression is not detected properly in this case. I am going to create a patch today for the workaround to work π
UPDATE: The patch is out. Take a look at tslint-react-hooks@2.1.0
Thanks, that did it
Awesome π Thanks for verifying it!
I am going to close the issue for now, as the workaround is fine and unless the React team finds a way to enhance the heuristic, there does not seem to be a way to fully fix it π
If someone has an idea, feel free to reopen the issue to discuss it or create a PR π