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

0

Issue

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);
}

Solution

You have two mistakes.

1- You defined getUpperGroups after useEffect, so you can’t add it to the list of useEffect dependencies.

2- if you add getUpperGroups to list of useEffect dependencies, useEffect will run on every re-render and you give a loop of re-render error.

So there is two solutions.

1- Add getUpperGroups into useEffect

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


useEffect(() => {
  
  const getUpperGroups = () => {

   let newUpperGroups = upperGroups;

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

   setUpperGroups(newUpperGroups);
  }

  getUpperGroups();
}, [contentGroupData]);

2- Disable eslint

useEffect(() => {
  getUpperGroups();
  setContentData(contentGroupData);

  // eslint-disable-line react-hooks/exhaustive-deps
}, [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);
}

Answered By – Hossein Mohammadi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More