Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 132 ยท Projects

Project: Tic-Tac-Toe with History

Build tic-tac-toe in React with winner detection and a move history you can jump back through. Learn immutable state, lifting state up and derived values in five runnable stages.

Tic-tac-toe is a small game with a big lesson: how to decide what is state and what is not. The board, whose turn it is, who won, which move you are looking at: some of these are real state, and the rest can be calculated. Getting that split right makes the final feature, jumping back to any earlier move, almost free.

We build the game in stages, and each stage is a complete program. You will use state, immutable updates, lifting state up, pure functions and lists with keys. The finished app has winner highlighting, draw detection, move locations, and a history list that can be sorted.

Planning the data

Think of the game as a short story: a sequence of boards. Each board is nine cells that hold 'X', 'O' or null, so a board is an array of nine values, indexed like this:

TEXT
 0 | 1 | 2
---+---+---
 3 | 4 | 5
---+---+---
 6 | 7 | 8

What do we need to know to draw the screen?

Question Where the answer comes from
What is in each cell? State: the board array
Whose turn is it? Derived: if an even number of moves were played, X is next
Did someone win? Derived: calculated from the board
Is it a draw? Derived: every cell is full and nobody won

The golden rule from choosing state structure applies: keep the minimal state and calculate the rest during render. In stage 1 we will cheat and store whose turn it is, to see why it later gets in the way.

Stage 1: a board that takes turns

We need a Square (one button), a Board (nine squares) and a way to remember the marks. For now everything lives in Board.

Stage 1: clicking squares

Study handleClick. It copies the array with slice(), changes the copy, and passes the copy to setSquares. Mutating squares directly would keep the same array reference, and React would not know anything changed (state updates). Two problems are visible straight away: you can click an occupied square and overwrite its mark, and the game never ends. Fix them with a rule engine.

Stage 2: winner calculation

Who won is a pure function of the board: same board in, same answer out. That makes it easy to write and to test, with no React involved. A winning line is any of eight triples of indexes (three rows, three columns, two diagonals).

Stage 2a: testing the winner function

The function returns null while the game goes on, an object with the winner and the winning line when someone has three in a row, and an object with draw: true when the board is full. Having the line will let us highlight the winning cells later.

Now use it. The click handler ignores clicks when the game is over or the square is taken, and the status text comes from the result, not from state:

Stage 2b: rules enforced

result is computed in every render and never stored. A game "ends" simply because calculateResult now returns something. Notice that status is also an ordinary local variable: derived text, not state.

Stage 3: lifting state up for time travel

To go back to an earlier move we must remember all earlier boards. So the single squares array becomes a history: an array of boards. That data has to be visible to two things: the board (to draw the current position) and a list of moves (to jump around). Neither can own it alone, so it moves up into a parent, Game. This is lifting state up. Board becomes a controlled component that receives everything through props and reports a play through a callback.

The state we keep is history and currentMove. Everything else is derived:

  • currentSquares = history[currentMove]
  • xIsNext = currentMove % 2 === 0

That second line is why we do not store xIsNext any more. After 0 moves X is next, after 1 move O is next, and so on. Storing it separately would invite bugs: jumping back to move 3 would need us to also fix xIsNext by hand. Derived values cannot go out of sync.

Stage 3: history and time travel

Play three moves, then press "Go to move #1" and play a different square. Moves 2 and 3 disappear: history.slice(0, currentMove + 1) keeps only the past up to the move you were viewing, and the new board is added after it, like undo followed by a new action. Never mutate the old history: each board stays a frozen snapshot, which is exactly why time travel is trivial. The history entries could use the move number as a key here because the list is only ever truncated or appended, never reordered. The sorted version in stage 4 reorders it for display, so we will look at keys again there.

Many small games and editors implement undo this way: store snapshots, keep a pointer. The cost is memory, which is irrelevant for nine cells but would matter for a large document. For big data you would store the actions and replay them (see reducers) or use structural sharing.

Stage 4: the finished game

The last stage adds the features that turn it from an exercise into a pleasant game:

  1. Highlight the winning line, using the line we already return.
  2. Show where each move was made, as "(column, row)". Instead of storing bare boards we store { squares, index } entries.
  3. Mark the current move with plain text rather than a button, since you are already there.
  4. Toggle ascending or descending order of the move list. This is a view preference, so it is its own useState, and the list is sorted at render time without touching history.
  5. Accessible squares. Each button gets an aria-label such as "Row 1, column 2, X", and the status line is a live region so screen readers hear the result.

Because the moves list can now be reversed, keys matter: we use the move number, which identifies an entry stably in both orders.

Stage 4: the complete game

Play out a win: X in the top row. The three cells turn green, further clicks do nothing, and the history stays available, so you can step back and branch into a different game. Press the sort button and the list reverses without any change to history or currentMove.

Why this design works

  • One source of truth. history plus currentMove determine everything on screen. The board, the status, the next player, the winning line and the move labels are all calculated.
  • State flows down, events flow up. Game passes data to Board as props, and Board reports plays through onPlay. Square only knows how to look and how to say "I was clicked".
  • Pure rules. calculateResult and describePosition have no hidden inputs, so they are trivially testable and safe to call in render.
  • Immutability. Every board is a new array and no earlier board is ever changed, so jumping back is just choosing another index.

When a feature looks hard, check whether your state shape is the obstacle. Time travel was awkward in a world where we stored "whose turn it is". Once that became derived from currentMove, the feature needed almost no new code.

Ideas to extend it

  1. Reset. Add a "New game" button that sets history back to a single empty board.
  2. Scoreboard. Count wins in a state object keyed by player, updated when a game ends. Think about whether to update it in an event handler or an effect (the answer is the handler, see you might not need an effect).
  3. Larger board. Make the size a constant and generate the winning lines with loops instead of a list.
  4. A computer opponent. After the player's move, pick the first winning or blocking square. Keep the AI as a pure function of the board.
  5. Reducer version. Rewrite Game with useReducer and actions played and jumped (useReducer).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does handleClick copy the squares array with slice() before changing it?

    Mutating the existing array keeps the same reference, so React cannot tell state changed. A copy also keeps old boards intact for the history.
  2. 2. In the final game, which values are derived rather than stored in state?

    The only state is history, currentMove and the sort order. Whose turn it is comes from currentMove, the board from history[currentMove], and the result from calculateResult.
  3. 3. After going back to move 2 and playing a new square, what happens to the old moves 3, 4 and 5?

    handlePlay builds [...history.slice(0, currentMove + 1), newEntry], so the abandoned future is dropped, like undo followed by a new action.
  4. 4. Why is the history list sorted at render time instead of reversing the history state?

    currentMove is an index into history. The order in which the list is displayed does not change the game, so it is kept as a separate flag.
  5. 5. Why does Board receive squares and onPlay as props instead of owning the squares?

    Both the board and the move list need the history, so the state lives in their closest common parent. Board is a controlled component.

Summary

  • Decide what is state and what is derived: only history, currentMove and the sort order are state; turn, board, winner and status are calculated.
  • Never mutate state. Copy the board, change the copy, and keep every old board as a snapshot.
  • Put game rules in pure functions such as calculateResult, which are easy to test without a UI.
  • Lift state to the closest common parent (Game) when several components need it; children receive props and call callbacks.
  • Time travel is a pointer into an array of snapshots; playing after jumping back truncates the future with slice.
  • Add accessibility as you go: descriptive aria-labels, a live status region and buttons for moves.

Next: Project: Shopping Cart