Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 916
aliosmankepir Avatar asked Sep 11 '25 05:09

aliosmankepir


2 Answers

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

like image 148
Hend El-Sahli Avatar answered Sep 14 '25 16:09

Hend El-Sahli


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 (
  ..
)}
like image 30
Abdelmonaem Shahat Avatar answered Sep 14 '25 15:09

Abdelmonaem Shahat