React Snake Game (Grid + Food + Collision)

hard
By FrontendAtlas Editorial · Updated Nov 23, 2026
hard level
React hooks (useState/useEffect/useMemo)Interval lifecycle managementKeyboard event handlingImmutable state updates for moving/growing arrays
Build a Snake game in React using a grid board. Support keyboard controls, food spawning, score updates, and game-over handling for wall/body collisions.

Requirements

  • Render a fixed-size board (for example 14×14) with snake body and food cells.
  • Move the snake using Arrow keys (optionally WASD).
  • Run game ticks on an interval while the game is running.
  • Eating food should grow the snake and increment score.
  • Colliding with walls or snake body should end the game.
  • Provide Start/Pause and Reset controls.
  • Expose score and current snake length in the UI.
  • Buffer at most one valid perpendicular turn per tick. Validate it against the committed movement direction; same/opposite inputs do not consume the buffer.
  • When the snake fills the board, render “You win”, stop movement, and render no food cell.

What the checks look for

The checks find elements by .cell, .cell--snake, .cell--food, text "Score: 0", text "Length: 3", text "Paused", button "Start", text "Running", button "Pause", body, text "Game over", text "Score: 1", text "Length: 4", .cell--food.cell--snake, button "Reset". Keep these in your markup.

Expected behavior

  • Initial state shows a short snake, one food cell, and score 0.
  • Press Start to begin movement; snake advances one cell per tick.
  • When head reaches food, score increases and snake length grows by 1.
  • RIGHT → UP → LEFT during one tick commits UP; only the first valid perpendicular turn is buffered.
  • Hitting boundary or own body stops the game and shows game-over state.
  • Reset returns to initial state with a new food position.
  • Filling the last free cell stops the timer, renders “You win”, and leaves no food cell.

Implementation notes

  • Store snake as ordered coordinates, with index 0 as the head.
  • Keep committed direction and the nullable one-turn buffer in synchronous refs. Key events can arrive before React commits state, so every handler must see an already-occupied buffer immediately; clear it when the tick commits.
  • Use Set/string keys for fast cell occupancy checks.
  • Generate food only on free cells that are not occupied by snake.
  • Clear interval correctly on pause, game over, and unmount.

Solution idea

Keep snake coordinates, food, score, and run state in React state, but keep committed direction and the nullable input buffer in synchronously updated refs. That makes a second keydown observe the first buffered turn even before React commits a render. Tick with setInterval, prepend the next head, and pop the tail unless food is eaten. Treat a full board as a win: food becomes null, the loop stops, and no food cell renders.