React useEffect dependency array: what to include

Viewed 157

I am developing a small Tic-Tac-Toe game in react and it's working as I want it to do. Everything's fine except the es-linter and I don't want to just disable a rule as that's probably a bug. So here is one of two hooks I have, where the problem occurs:¨

useEffect(() => {
  if (
    board !== initialState.board &&
    firstTurnIsPlayed() &&
    players[currentPlayerIndex].bot
  ) {
    // Select random empty tile
    const emtpyTiles = getEmptyTiles(board);
    const randomTileIndex = Math.floor(Math.random() * emtpyTiles.length);
    const randomTile = emtpyTiles[randomTileIndex];

    placeCurrentPlayerOnCoordinate(randomTile);
  }
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentPlayerIndex]);

board players currentPlayerIndex are states, initialState is a constant with the initial state values, firstTurnIsPlayer is a local function only using currentPlayerIndex

So this is what I'm using right now and it's working like a charm. Whenever currentPlayerIndex changes and therefore it's a new turn of the next player, I'm checking if the new currentPlayer is a bot. If he's a bot, I'll automatically place his symbol on a random empty tile, otherwise I do nothing but waiting for the player to click on an empty tile.

That's how I want it to have, but not how the linter wants to, because I don't put all the other variables I use into the dependency array. I understand that I should do that in order to make sure my hook doesn't use wrong(not up-to-date) values of variables. On the other hand, if I add these variables to the dependencies array, the hook gets executed every time one of the vars in the array changes and that's way too often and in situations I don't want it to.

So my question right now is:

How can I satisfy my linter while also maintaining my working functionality?

0 Answers
Related