3

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?

Oldie55
  • 31
  • 3
  • The linter is supposed to remind you of best practices according to YOUR rules. It's not generally useful to just use default/someone else's linter settings and then worry about it, sometimes just disabling it is fine. – fesieg Sep 25 '20 at 08:44
  • 1
    You can't really. The rule configuration for hooks is pretty simple, on/off and warn/error. I recommend to my team to follow what the linter recommends (figure out what checks to use with all the dependencies) unless there is really good reason not to, and in those cases we disable the linter for that line and require a comment with explanation so if the effect callback is updated the next person has a better visual queue to re-check dependencies. Once disabled it won't/can't catch future errors/issues. – Drew Reese Sep 25 '20 at 08:44

0 Answers0