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
}
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";
)
Your eslint config also does not work for me, but this one does:
"eslintConfig": {
"extends": "react-app"
}
I added the following dependencies: @typescript-eslint/eslint-plugin
and @typescript-eslint/parser
to package.json
and added the following to .eslintrc.js
:
extends: [... 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended']
parser: '@typescript-eslint/parser',
plugins: [..., '@typescript-eslint'],
You should not be using hooks within conditions. This will cause errors, because the only way react knows how to associate stateful values to variables is by order, which in this case will not be consistent.
check out the docs, they spell out the rules of hooks. https://reactjs.org/docs/hooks-rules.html
what you want is something more like this
const [a, setA] = useState(initialVal)
if (Math.random() > 0.5){
setA(0)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.