I'm using react 16.8, and eslint-plugin-react-hooks 1.6.0 .When I use hooks conditionally, I hoped eslint was going to warn me. Here is my config :
"eslintConfig": {
"parser": "babel-eslint",
"plugins": [
"react-hooks"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
If I use hooks conditionally in custom hooks, there will be a warning like this: "React Hook \"useState\" is called conditionally. React Hooks must be called in the exact same order in every component render."
function useCustomHook() {
if (Math.random() > 0.5){
const [a, setA] = useState(0)
}
}
but if I use hooks in function component, it does't work.
function MyComponent() {
if (Math.random() > 0.5){
const [a, setA] = useState(0)
}
return null
}
React basically knows which useEffect hook is which, basically by counting invocations. Calling useEffect conditionally is bad, specifically because the amount of times useEffect gets called cannot change. Your example is conditional, but React can't detect it because in either condition you call it once.
This ESLint plugin enforces the Rules of Hooks. It is a part of the Hooks API for React.
Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs. Avoiding such situations ensures that Hooks are called in the correct order each time the component renders.
This is what worked for me:
$ npm i --save-dev eslint-plugin-react-hooks
{
"plugins": [
...
"react-hooks"
],
"rules": {
...
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
...
$ npm i --save-dev eslint-config-react-app
{
...
"extends": "react-app"
$ npm i --save-dev eslint-plugin-flowtype
$ npm i --save-dev eslint@^5.0.0
Actually, when I paste your function on the App.js file created by create-react-app, there is the expected error when running the app.
Maybe your function isn't considered a React Component (your function is considered a common function). Make sure you have React on scope (import React from "react";
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With