4

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 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

You shouldn't disable ALL warnings ever. Specify which warning to disable it, and ideally leave a comment in code doing so as well, especially for a warning where the docs claim code triggering it is always wrong...
2

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.

Comments

1

Move changeCount inside useEffect

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

    changeCount();
  },[])

  return (
  ..
  )
}

Comments

0

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

2 Comments

I think even suggesting to disable that whole rule is a terrible idea.
I think so :) But it is just some way to solve it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.