How to fix "React Hook useEffect has a missing dependency. Either include it or remove the dependency array" problem?

Samet Sunman picture Samet Sunman · Oct 23, 2020 · Viewed 8.4k times · Source

I want to use useEffect, but when I add getUpperGroup method, I get warning:

React Hook useEffect has a missing dependency: 'getUpperGroups'. Either include it or remove the dependency array"

My code is:

useEffect(() => {
  getUpperGroups();
  setContentData(contentGroupData);
}, [contentGroupData]);


const [contentData, setContentData] = useState<Fundation[]>([] as Fundation[]);
const [upperGroups, setUpperGroups] = useState({});

const getUpperGroups = () => {

   let newUpperGroups = upperGroups;

   contentGroupData.forEach(content=>{
     newUpperGroups = {...newUpperGroups, [content.id]: content.title};
   })

   setUpperGroups(newUpperGroups);
}

Answer

JeannotMn picture JeannotMn · Oct 23, 2020

You can either:

  1. Suppress that rule for the entire project: Go to .eslintrc file and change 'react-hooks/exhaustive-deps': 'error' to 'react-hooks/exhaustive-deps': 'warn' or 'react-hooks/exhaustive-deps': 'off'

  2. Supress the rule only in this instance:

useEffect(() => {
    getUpperGroups();
    setContentData(contentGroupData);
}, [contentGroupData]);


const [contentData, setContentData] = useState<Fundation[]>([] as Fundation[]);
const [upperGroups, setUpperGroups] = useState({});

const getUpperGroups = () => {

    let newUpperGroups = upperGroups;

    contentGroupData.forEach(content=>{
        newUpperGroups = {...newUpperGroups, [content.id]: content.title};
    })

    setUpperGroups(newUpperGroups);
} // eslint-disable-line react-hooks/exhaustive-deps