Hi, it’s that Snake again giving me headaches.
Here’s a codesandbox with only the relevant parts:
The SnakeGame component holds the state that is relevant for the game (snake position, direction, intervalTime).
I’m using useEffect with an empty array to attach the keyboard event listeners which set the direction of the snake.
The App component holds the two states of the game (isStart, isPause) and passes them down as props to the SnakeGame component.
Depending on a combination of those two Booleans, SnakeGame can either be in “running” mode, in “pause” mode or in “stop/reset” mode.
The bug of the game is now that the user can change the direction of the snake in all modes. Naturally, I only want the direction to be set when the game is in “running” mode. And I can’t for the hell of it figure out how to do that, because I can’t add any dependencies to the useEffect hook which attaches the event listeners. I don’t want to remove the listeners on every pause/stop of the game, I only want to be able to define a condition whether the direction should be set or not.
I’ve been struggling with this for days. What I really like about React that it seems to force “separation of concerns” on me, which is nice because my functions have a tendency to be a bit messy, but it’s really causing me trouble in this case.
