Skip to main content
05

Tic-tac-toe

Mediumreactstatederived statea11y

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build a tic-tac-toe game for two players sharing one screen. The project is already set up with React, a static board and some styles: make it playable.

Requirements

  • The board is a 3×3 grid. Players take turns, and X always moves first.
  • Clicking an empty cell places the current player's mark. Clicking a filled cell does nothing.
  • Above the board, a status line shows whose turn it is (Player X turn), the winner (Player O wins!) or Draw! when the board is full with no winner.
  • Once someone wins, no more moves can be made.
  • The Reset button starts a new game.

Accessibility

  • Every cell is a <button> with a label that says its position and content, e.g. Cell 5, X or Cell 1, empty.
  • The status line is announced to screen readers when it changes (aria-live).

Note

The preview updates as you type. There are no automated tests for this challenge yet: play a few games to check the win, draw and reset cases, then compare with the reference solution.

Follow-ups interviewers ask

  • Make the board size configurable: an N×N board where M marks in a row win.
  • Highlight the winning line.
  • Add undo, or a move history you can jump back through.

The approach

The key decision is what goes in state. The only thing that changes on its own is the board: an array of 9 cells, each 'X', 'O' or null. Everything else can be computed from it on every render:

  • Whose turn: count the marks. An even count means X is next, odd means O.
  • Winner: check the 8 possible lines (3 rows, 3 columns, 2 diagonals) for three equal marks.
  • Draw: no winner and every cell is filled.

Keeping currentPlayer or winner in their own useState is the most common mistake in this round. It works until one update forgets to set them, and then the UI contradicts itself. Derived state can't go out of sync.

Loading diagram...

Updating the board

play(index) returns early if the cell is taken or the game is over, then writes the mark immutably with map, so React sees a new array. Mutating board[index] and calling setBoard(board) would not re-render, because the reference didn't change.

The cells are disabled once filled or once there is a winner. That gives keyboard and screen reader users the same rules as mouse users, without extra checks.

Accessibility

  • Real <button> elements give focus, Enter and Space for free.
  • aria-label reads Cell 5, X instead of just X, so the position is clear.
  • aria-live="polite" on the status announces turns and the result.

Complexity

Each render checks 8 lines: O(1) for a 3×3 board. For an N×N board with M in a row, check only the lines through the last move: O(M) per move instead of scanning the whole board.

What interviewers look for

  • Minimal state and derived values, not duplicated state.
  • Immutable updates.
  • Win detection written as data (the list of lines), not a long chain of ifs.
  • Accessibility without being asked.

Reference solution

src/App.js

jsx
import { useState } from 'react'

const LINES = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
]

function getWinner(board) {
  for (const [a, b, c] of LINES) {
    if (board[a] && board[a] === board[b] && board[a] === board[c]) return board[a]
  }
  return null
}

export default function App() {
  // The board is the only state. Whose turn it is and who won are derived from it.
  const [board, setBoard] = useState(() => Array(9).fill(null))

  const winner = getWinner(board)
  const isDraw = !winner && board.every(Boolean)
  const player = board.filter(Boolean).length % 2 === 0 ? 'X' : 'O'
  const status = winner ? `Player ${winner} wins!` : isDraw ? 'Draw!' : `Player ${player} turn`

  function play(index) {
    if (board[index] || winner) return
    setBoard((current) => current.map((cell, i) => (i === index ? player : cell)))
  }

  return (
    <main className="game">
      <p className="status" aria-live="polite">
        {status}
      </p>
      <div className="board">
        {board.map((cell, index) => (
          <button
            key={index}
            type="button"
            className="cell"
            aria-label={`Cell ${index + 1}, ${cell ?? 'empty'}`}
            disabled={Boolean(cell) || Boolean(winner)}
            onClick={() => play(index)}
          >
            {cell}
          </button>
        ))}
      </div>
      <button type="button" className="reset" onClick={() => setBoard(Array(9).fill(null))}>
        Reset
      </button>
    </main>
  )
}