2
votes

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 (
  ..
  )}

5

5 Answers

2
votes

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 (
  ..
)}
2
votes

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.

1
votes

Move changeCount inside useEffect

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

    changeCount();
  },[])

  return (
  ..
  )
}
1
votes

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 ...

-1
votes

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