Search code examples
javascriptreactjseslinteslint-plugin-react-hooks

React useEffect is complaining about missing dependency even after destructuring


Before you mark this as a duplicate - please understand that I have tried following most of the articles here on SO but none of them seem to help me out, perhaps I am overlooking something or I am having a brain fart today. So please excuse me for asking this question again.

In my component , I have the following code gist.

  let { teamid } = props.currentTeam
  useEffect(() => {
    if (teamid) {
      props.teamMembers(teamid);
    }
  }, [teamid]);

As you can verify from the code above , I am only using teamid in my useEffect. I am not using the entire props object. However, React stil complains with this message

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

Please let me know what I am doing wrong here. Any help will be well appreciated.


Solution

  • Basically what the react-hooks/exhaustive-deps warning is telling you is that you're still referencing the props object within the effect, which you are - you're not destructuring the props item out fully:

    let { teamid } = props.currentTeam
    useEffect(() => {
      if (teamid) {
        props.teamMembers(teamid); // PROPS STILL REFERENCED - ISSUE
      }
    }, [teamid]); // NO DEPENDENCY FOR PROPS - ISSUE
    

    Destructure the props object fully and include all the dependencies - with this the props object can update, and if the currentTeam or teamMembers properties don't change then your effect doesn't either:

    const { currentTeam, teamMembers } = props // FULLY DESTRUCTURED
      
    useEffect(() => {
      if (currentTeam.teamid) {
        teamMembers(currentTeam.teamid)
      }
    }, [currentTeam.teamid, teamMembers]) // NO PROPS DEPENDENCIES