Skip to content
D
Documentation

Build a tic-tac-toe game

how-to
4 min readUpdated

Use this example to connect a playable board and a move list to shared Zustand state. You get alternating turns, winner and draw detection, and buttons that let you revisit earlier boards.

Start from the project in the React quick start. Keep its dependencies, stylesheet import, and StrictMode wrapper. No additional package is needed: the game uses create from the installed zustand package.

Building a game

Keep the board snapshots and selected move in one store. Derive the next player from the selected move instead of storing a second value that needs to stay synchronized. Game reads the store and passes the selected board to Board; each Square receives its value and click handler through props.

  1. Add the game rules below. These are application types and helpers, not Zustand APIs.
  2. Use the helpers in the board component in the next section. calculateWinner() checks the eight winning lines and returns 'X', 'O', or null. calculateTurns() counts empty squares, and calculateStatus() produces the text above the board.
ts
export type Player = 'X' | 'O'
export type Cell = Player | null
export type Squares = Cell[]

export function calculateWinner(squares: Squares): Cell {
  const lines: [number, number, number][] = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]

  for (const [a, b, c] of lines) {
    const value = squares[a]
    if (value && value === squares[b] && value === squares[c]) {
      return value
    }
  }

  return null
}

export function calculateTurns(squares: Squares): number {
  return squares.filter((square) => square === null).length
}

export function calculateStatus(
  winner: Cell,
  turns: number,
  player: Player,
): string {
  if (!winner && !turns) return 'Draw'
  if (winner) return `Winner ${winner}`
  return `Next player: ${player}`
}

The square values have three meanings:

ValueMeaning
nullEmpty square, available for a move.
'X'A move by X, who plays first.
'O'A move by O, who plays second.

Building the board

  1. Add src/Board.tsx. Square displays one value; Board arranges nine squares in a three-by-three grid with an explicit width and height.
  2. In handleClick(), reject occupied squares and moves after a win. Copy the array with slice(), put the current player's mark in the copy, and pass it to onPlay.
tsx
import {
  calculateStatus,
  calculateTurns,
  calculateWinner,
} from './game-rules'
import type { Cell, Player, Squares } from './game-rules'

type SquareProps = {
  value: Cell
  position: number
  onSquareClick: () => void
}

function Square({ value, position, onSquareClick }: SquareProps) {
  return (
    <button
      type="button"
      aria-label={`Square ${position}: ${value ?? 'empty'}`}
      onClick={onSquareClick}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 0,
        backgroundColor: '#fff',
        color: '#222',
        border: '1px solid #999',
        borderRadius: 0,
        fontSize: '1.5rem',
        fontWeight: 'bold',
      }}
    >
      {value}
    </button>
  )
}

type BoardProps = {
  xIsNext: boolean
  squares: Squares
  onPlay: (nextSquares: Squares) => void
}

export default function Board({ xIsNext, squares, onPlay }: BoardProps) {
  const winner = calculateWinner(squares)
  const turns = calculateTurns(squares)
  const player: Player = xIsNext ? 'X' : 'O'
  const status = calculateStatus(winner, turns, player)

  function handleClick(index: number) {
    if (squares[index] || winner) return
    const nextSquares = squares.slice()
    nextSquares[index] = player
    onPlay(nextSquares)
  }

  return (
    <section aria-label="Game board">
      <p aria-live="polite">{status}</p>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gridTemplateRows: 'repeat(3, 1fr)',
          width: 180,
          height: 180,
          border: '1px solid #999',
        }}
      >
        {squares.map((square, index) => (
          <Square
            key={index}
            value={square}
            position={index + 1}
            onSquareClick={() => handleClick(index)}
          />
        ))}
      </div>
    </section>
  )
}

Once mounted below, clicking an empty square displays X or O. A winning board displays Winner X or Winner O; a full board without a winner displays Draw.

Adding time travel

  1. Add a store with history, initially containing one empty board, and currentMove, initially zero. Keep snapshots rather than overwriting the previous board.
  2. Give the store actions for updating each field. As in the authors' example, each action accepts either a value or an updater function. set merges the returned field into the state, preserving the other field and the actions.
ts
import { create } from 'zustand'
import type { Squares } from './game-rules'

type GameState = {
  history: Squares[]
  currentMove: number
  setHistory: (
    nextHistory: Squares[] | ((history: Squares[]) => Squares[]),
  ) => void
  setCurrentMove: (
    nextCurrentMove: number | ((currentMove: number) => number),
  ) => void
}

export const useGameStore = create<GameState>()((set) => ({
  history: [Array.from({ length: 9 }, () => null)],
  currentMove: 0,
  setHistory: (nextHistory) => {
    set((state) => ({
      history:
        typeof nextHistory === 'function'
          ? nextHistory(state.history)
          : nextHistory,
    }))
  },
  setCurrentMove: (nextCurrentMove) => {
    set((state) => ({
      currentMove:
        typeof nextCurrentMove === 'function'
          ? nextCurrentMove(state.currentMove)
          : nextCurrentMove,
    }))
  },
}))

The rendered game below reads history[currentMove]. Changing currentMove selects a snapshot without changing the history. Even move numbers give X the next turn; odd numbers give O the next turn.

Showing the past moves

  1. Add src/Game.tsx. Select the two state fields and two actions separately. The hook connects the component to store updates; no provider or manual subscription is needed.
  2. Map the history to buttons. jumpTo() selects the requested move. handlePlay() retains history through the selected move, appends the new board, and selects it. Playing after a jump replaces the later branch of moves.
tsx
import Board from './Board'
import { useGameStore } from './game-store'
import type { Squares } from './game-rules'

export default function Game() {
  const history = useGameStore((state) => state.history)
  const setHistory = useGameStore((state) => state.setHistory)
  const currentMove = useGameStore((state) => state.currentMove)
  const setCurrentMove = useGameStore((state) => state.setCurrentMove)
  const xIsNext = currentMove % 2 === 0
  const currentSquares = history[currentMove]!

  function handlePlay(nextSquares: Squares) {
    const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]
    setHistory(nextHistory)
    setCurrentMove(nextHistory.length - 1)
  }

  function jumpTo(nextMove: number) {
    setCurrentMove(nextMove)
  }

  return (
    <main style={{ minHeight: 400, padding: 24, fontFamily: 'monospace' }}>
      <h1>Tic-tac-toe</h1>
      <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
        <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
        <section aria-label="Past moves">
          <h2>Past moves</h2>
          <ol>
            {history.map((_, historyIndex) => (
              <li key={historyIndex}>
                <button
                  type="button"
                  aria-current={historyIndex === currentMove ? 'step' : undefined}
                  onClick={() => jumpTo(historyIndex)}
                >
                  {historyIndex > 0
                    ? `Go to move #${historyIndex}`
                    : 'Go to game start'}
                </button>
              </li>
            ))}
          </ol>
        </section>
      </div>
    </main>
  )
}
  1. In src/main.tsx, replace import Counter from './Counter.tsx' with import Game from './Game.tsx' and <Counter /> with <Game />, keeping the rest of the React quick start's mounting code unchanged.

  2. Build and run your project:

bash
npm run build
npm run dev

Open the URL printed by Vite. You see nine empty squares, Next player: X, and a Go to game start button. Each legal move adds a move button. Click squares 1, 4, 2, 5, and 3, in that order, to give X the top row and display Winner X. Click Go to move #2 to display the board after two moves with X next. Click a different empty square to start a new branch; the former later moves disappear from the list.

Props that control the board

These are the example's application props, not Zustand configuration options. All three are required and have no defaults.

PropTypeDefaultWhat it does
xIsNextbooleanNoneChooses X when true, O when false.
squaresSquaresNoneSupplies the nine cells of the selected snapshot.
onPlay(nextSquares: Squares) => voidNoneReceives a copied board after a legal move.

Keep snapshots and derived state consistent

Keep every stored board immutable so earlier move buttons still display the original snapshots. For the update rules behind this pattern, see Immutable state and merging.

Keep currentMove within the history's bounds. This UI obtains jump targets from the history itself and selects the last entry after appending. The non-null assertion on history[currentMove] expresses that application invariant.

Derive xIsNext, the winner, and the status from the selected snapshot and move number. They do not need their own store fields. For more computed selectors, see Select computed state.

Compare the game with the authors' interactive tic-tac-toe tutorial. Explore the live Zustand demo for another example of store-driven React UI.

Was this page helpful?

Build a tic-tac-toe game — zustand · GPT-6.1 Sol