Is it bad practice to use an object property instead of the object as a dependecy in the useEffect hook?

Viewed 732

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.

1 Answers

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
Related