You can check the app from this; Sandbox
The logic of the snake movement is removing one square from its back and adding a new head basically. This creates an appearance like moving. But my interval doesn't seem to work correctly.
It works only for once then it's doing the same thing over and over again. Which means that state is not changing at all after one time.
I saw this in a video where someone was developing this game exactly this way but it was working. I can't see what's wrong with this code, thanks in advance.
I saw your question. It was really interesting. The problem is this one.
useEffect(() => {
setInterval(moveSnake, 1000);
}, []);
setInterval(moveSnake, 1000). This is using origin moveSnake. As functional components overwrite the whole state and functions, moveSnake changes. I think pointer to the array changes. And as it's using the origin pointer, setInterval can not change the state. I think you can update as follow.
useEffect(() => {
setTimeOut(moveSnake, 1000);
}, [snakeDots]);
The "hidden" trick is that you are using snakeDots in your moveSnake method. Thus you will want to wait until it's done updating to trigger a new call.
You can make use of both useEffect and setTimeout to set a new timeout every time the snakeDots have been updated in the state. For example:
useEffect(() => {
setTimeout(moveSnake, 1000);
}, [snakeDots]);