简体   繁体   中英

React | React Hook useEffect has a missing dependency

I want to update a value in the store ONLY ONCE AT FIRST OPENING when the page is first opened using react hook. For this, I make the second parameter of useEffect '[]' empty list. Nothing prevents it from working, but I get a warning from ESLint rules: React Hook useEffect has a missing dependency: 'changeCount'. Either include it or remove the dependency array react-hooks/exhaustive-deps . How do I remove this warning?

const App = ({UserStore:{setCount, count}}) => {
  const changeCount = () => {
    setCount();
  }

  useEffect(() => {
    changeCount();
  },[])

  return (
  ..
  )}

use this syntax to remove this eslint warning before your dependency array like this:

const App = ({UserStore:{setCount, count}}) => {
const changeCount = () => {
    setCount();
}

useEffect(() => {
    changeCount();
    // eslint-disable-next-line
},[])

return (
  ..
)}

changeCount is a function that is not a setState or hooks. Since you use it in useEffect React will warn you. For the reason why it warns you read this article

Some of the answers above suggest you disable the checking, and I recommend diable only the one you are working on. However, normally you don't need to worry about a warning.

Move changeCount inside useEffect

const App = ({UserStore:{setCount, count}}) => {
  useEffect(() => {
    const changeCount = () => {
      setCount();
    }

    changeCount();
  },[])

  return (
  ..
  )
}

Create a custom hook...

export const useMountEffect = handler => useEffect(handler, []);

Consume it like

useMountEffect(() => {
  changeCount();
});

Not only you'll get rid of this warning... but it'll be more clear that this effect will only be executed onMount ...

TLDR

Fix eslint config "react-hooks/exhaustive-deps"

Answer

It is eslint error with hook, so how about fix eslint config like

{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
    "react-hooks/exhaustive-deps": "off" // Checks effect dependencies
  }
}

But It can make your hook be wrong action, So the other way you can use /* eslint-disable */

Reference

01. Rules of Hooks - React Document

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM