thisissami
thisissami

Reputation: 16343

How can I get `eslint-plugin-react-hooks` to lint functional components that are exported as `default`?

I have deliberately created a simple functional component that breaks the rules of hooks. It contains the following snippet.

  if (Math.rand > 0.5) {
    const [name, setName] = useState("fred");
  }

I expect that eslint-plugin-react-hooks would lint this clear mistake, but it doesn't. After trying to get to the bottom of this, I discovered that when I am exporting a function as default - the linter does not do it's thing. (I am using the @typescript-eslint/parser for what that's worth).

Is there any way to have the latter syntax work with eslint/eslint-plugin-react-hooks, or must I always create a named functional component, then run export default name; beneath the function?

https://codesandbox.io/s/hook-demo-c10y2

Upvotes: 1

Views: 1894

Answers (2)

Falady
Falady

Reputation: 124

Your code is breaking the rules of hooks at which a hook must only be called at the top level of your code. It cannot be placed inside an if...else statement. Check out the rules of hooks here: https://reactjs.org/docs/hooks-rules.html

Upvotes: -1

thisissami
thisissami

Reputation: 16343

So... I just discovered that this is a known bug with eslint-plugin-react-hooks. Seems like you need to have a named function for the plugin to catch & lint your errors. https://github.com/facebook/react/issues/14404 (specifically just the "react-hooks/rules-of-hooks" rule).

Upvotes: 2

Related Questions