5

I use the following code in my functional component. I want this component only to re-render when game._id changes. But React keeps giving me the warning:

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

Is this a dangerous practise or is it justified if I explicitly want it to depend on the given property?

  const [game, setGame] = useState({});

  useEffect(() => {
    return () => {
      if (game._id !== undefined) {
       // Do stuff with game
      }
    };
  }, [socket, user, game._id]);

I do not want to use game as a dependency, because that makes my component re-render way to much.

NickTheTramp
  • 185
  • 1
  • 10
  • see this answer https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook – shubham jha Jun 12 '21 at 15:26

1 Answers1

3

The dependency array checks if a value changed since the last render. It doesn't care where the value came from, or what it's shape. The problem is with the linter, that sees the use of game inside useEffect, although it's not registered as a dependency. Declare gameId and assign it the value of game._id, and use it as a dependency, and inside useEffect:

const [game, setGame] = useState({});

const gameId = game._id;

useEffect(() => {
  return () => {
    // use gameId inside useEffect
    if (gameId !== undefined) {
      // Do stuff with game
    }
  };
}, [socket, user, gameId]); // set gameId as dependency
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • This solution could help in the case when I only used the `game._id`, but I actually use the `game` object in that if statement (I should have made that more clear). So the linter still wants to see game as a dependency. – NickTheTramp Jun 13 '21 at 09:29
  • 1
    So it that case, `game` is a dependency, and you need to include it. – Ori Drori Jun 13 '21 at 09:31