Skip to content
Myr

tutorial-tic-tac-toe.md

This file

Path

docs/learn/guides/tutorial-tic-tac-toe.md

1,429 lines · 40.9 KiB · Markdown

Last changed by

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

History of this file

Take it

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1–466why, one step back
1---
2title: 'Tutorial: Tic-Tac-Toe'3description: Building a game4nav: 35---67# Tutorial: Tic-Tac-Toe89## Building a game1011You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing12React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React13app, and fully understanding it will give you a deep understanding of React and Zustand.1415> [!NOTE]16> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly17> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.1819The tutorial is divided into several sections:2021- Setup for the tutorial will give you a starting point to follow the tutorial.22- Overview will teach you the fundamentals of React: components, props, and state.23- Completing the game will teach you the most common techniques in React development.24- Adding time travel will give you a deeper insight into the unique strengths of React.2526### What are you building?2728In this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.2930You can see what it will look like when you're finished here:3132```jsx33import { create } from 'zustand'34import { combine } from 'zustand/middleware'3536const useGameStore = create(37 combine(38 {39 history: [Array(9).fill(null)],40 currentMove: 0,41 },42 (set, get) => {43 return {44 setHistory: (nextHistory) => {45 set((state) => ({46 history:47 typeof nextHistory === 'function'48 ? nextHistory(state.history)49 : nextHistory,50 }))51 },52 setCurrentMove: (nextCurrentMove) => {53 set((state) => ({54 currentMove:55 typeof nextCurrentMove === 'function'56 ? nextCurrentMove(state.currentMove)57 : nextCurrentMove,58 }))59 },60 }61 },62 ),63)6465function Square({ value, onSquareClick }) {66 return (67 <button68 style={{69 display: 'inline-flex',70 alignItems: 'center',71 justifyContent: 'center',72 padding: 0,73 backgroundColor: '#fff',74 border: '1px solid #999',75 outline: 0,76 borderRadius: 0,77 fontSize: '1rem',78 fontWeight: 'bold',79 }}80 onClick={onSquareClick}81 >82 {value}83 </button>84 )85}8687function Board({ xIsNext, squares, onPlay }) {88 const winner = calculateWinner(squares)89 const turns = calculateTurns(squares)90 const player = xIsNext ? 'X' : 'O'91 const status = calculateStatus(winner, turns, player)9293 function handleClick(i) {94 if (squares[i] || winner) return95 const nextSquares = squares.slice()96 nextSquares[i] = player97 onPlay(nextSquares)98 }99100 return (101 <>102 <div style={{ marginBottom: '0.5rem' }}>{status}</div>103 <div104 style={{105 display: 'grid',106 gridTemplateColumns: 'repeat(3, 1fr)',107 gridTemplateRows: 'repeat(3, 1fr)',108 width: 'calc(3 * 2.5rem)',109 height: 'calc(3 * 2.5rem)',110 border: '1px solid #999',111 }}112 >113 {squares.map((_, i) => (114 <Square115 key={`square-${i}`}116 value={squares[i]}117 onSquareClick={() => handleClick(i)}118 />119 ))}120 </div>121 </>122 )123}124125export default function Game() {126 const history = useGameStore((state) => state.history)127 const setHistory = useGameStore((state) => state.setHistory)128 const currentMove = useGameStore((state) => state.currentMove)129 const setCurrentMove = useGameStore((state) => state.setCurrentMove)130 const xIsNext = currentMove % 2 === 0131 const currentSquares = history[currentMove]132133 function handlePlay(nextSquares) {134 const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]135 setHistory(nextHistory)136 setCurrentMove(nextHistory.length - 1)137 }138139 function jumpTo(nextMove) {140 setCurrentMove(nextMove)141 }142143 return (144 <div145 style={{146 display: 'flex',147 flexDirection: 'row',148 fontFamily: 'monospace',149 }}150 >151 <div>152 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />153 </div>154 <div style={{ marginLeft: '1rem' }}>155 <ol>156 {history.map((_, historyIndex) => {157 const description =158 historyIndex > 0159 ? `Go to move #${historyIndex}`160 : 'Go to game start'161162 return (163 <li key={historyIndex}>164 <button onClick={() => jumpTo(historyIndex)}>165 {description}166 </button>167 </li>168 )169 })}170 </ol>171 </div>172 </div>173 )174}175176function calculateWinner(squares) {177 const lines = [178 [0, 1, 2],179 [3, 4, 5],180 [6, 7, 8],181 [0, 3, 6],182 [1, 4, 7],183 [2, 5, 8],184 [0, 4, 8],185 [2, 4, 6],186 ]187188 for (let i = 0; i < lines.length; i++) {189 const [a, b, c] = lines[i]190 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {191 return squares[a]192 }193 }194195 return null196}197198function calculateTurns(squares) {199 return squares.filter((square) => !square).length200}201202function calculateStatus(winner, turns, player) {203 if (!winner && !turns) return 'Draw'204 if (winner) return `Winner ${winner}`205 return `Next player: ${player}`206}207```208209### Building the board210211Let's start by creating the `Square` component, which will be a building block for our `Board`212component. This component will represent each square in our game.213214The `Square` component should take `value` and `onSquareClick` as props. It should return a215`<button>` element, styled to look like a square. The button displays the value prop, which can be216`'X'`, `'O'`, or `null`, depending on the game's state. When the button is clicked, it triggers the217`onSquareClick` function passed in as a prop, allowing the game to respond to user input.218219Here's the code for the `Square` component:220221```jsx222function Square({ value, onSquareClick }) {223 return (224 <button225 style={{226 display: 'inline-flex',227 alignItems: 'center',228 justifyContent: 'center',229 padding: 0,230 backgroundColor: '#fff',231 border: '1px solid #999',232 outline: 0,233 borderRadius: 0,234 fontSize: '1rem',235 fontWeight: 'bold',236 }}237 onClick={onSquareClick}238 >239 {value}240 </button>241 )242}243```244245Let's move on to creating the Board component, which will consist of 9 squares arranged in a grid.246This component will serve as the main playing area for our game.247248The `Board` component should return a `<div>` element styled as a grid. The grid layout is achieved249using CSS Grid, with three columns and three rows, each taking up an equal fraction of the available250space. The overall size of the grid is determined by the width and height properties, ensuring that251it is square-shaped and appropriately sized.252253Inside the grid, we place nine Square components, each with a value prop representing its position.254These Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user255interactions.256257Here's the code for the `Board` component:258259```jsx260export default function Board() {261 return (262 <div263 style={{264 display: 'grid',265 gridTemplateColumns: 'repeat(3, 1fr)',266 gridTemplateRows: 'repeat(3, 1fr)',267 width: 'calc(3 * 2.5rem)',268 height: 'calc(3 * 2.5rem)',269 border: '1px solid #999',270 }}271 >272 <Square value="1" />273 <Square value="2" />274 <Square value="3" />275 <Square value="4" />276 <Square value="5" />277 <Square value="6" />278 <Square value="7" />279 <Square value="8" />280 <Square value="9" />281 </div>282 )283}284```285286This Board component sets up the basic structure for our game board by arranging nine squares in a2873x3 grid. It positions the squares neatly, providing a foundation for adding more features and288handling player interactions in the future.289290### Lifting state up291292Each `Square` component could maintain a part of the game's state. To check for a winner in a293tic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9294`Square` components.295296How would you approach that? At first, you might guess that the `Board` component needs to ask each297`Square` component for that `Square`'s component state. Although this approach is technically298possible in React, we discourage it because the code becomes difficult to understand, susceptible299to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the300parent `Board` component instead of in each `Square` component. The `Board` component can tell each301`Square` component what to display by passing a prop, like you did when you passed a number to each302`Square` component.303304> [!IMPORTANT]305> To collect data from multiple children, or to have two or more child components306> communicate with each other, declare the shared state in their parent component instead. The307> parent component can pass that state back down to the children via props. This keeps the child308> components in sync with each other and with their parent.309310Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state311variable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:312313```jsx314import { create } from 'zustand'315import { combine } from 'zustand/middleware'316317const useGameStore = create(318 combine({ squares: Array(9).fill(null) }, (set) => {319 return {320 setSquares: (nextSquares) => {321 set((state) => ({322 squares:323 typeof nextSquares === 'function'324 ? nextSquares(state.squares)325 : nextSquares,326 }))327 },328 }329 }),330)331332export default function Board() {333 const squares = useGameStore((state) => state.squares)334 const setSquares = useGameStore((state) => state.setSquares)335336 return (337 <div338 style={{339 display: 'grid',340 gridTemplateColumns: 'repeat(3, 1fr)',341 gridTemplateRows: 'repeat(3, 1fr)',342 width: 'calc(3 * 2.5rem)',343 height: 'calc(3 * 2.5rem)',344 border: '1px solid #999',345 }}346 >347 {squares.map((square, squareIndex) => (348 <Square key={squareIndex} value={square} />349 ))}350 </div>351 )352}353```354355`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The356`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the357array corresponds to the value of a square. When you fill the board in later, the squares array358will look like this:359360```js361const squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]362```363364Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty365squares.366367Next, you need to change what happens when a `Square` component is clicked. The `Board` component368now maintains which squares are filled. You'll need to create a way for the `Square` component to369update the `Board`'s component state. Since state is private to a component that defines it, you370cannot update the `Board`'s component state directly from `Square` component.371372Instead, you'll pass down a function from the Board component to the `Square` component, and you'll373have `Square` component call that function when a square is clicked. You'll start with the function374that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:375376Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name377`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the378`onSquareClick` prop of the first Square component:379380```jsx381<Square key={squareIndex} value={square} onSquareClick={() => handleClick(i)} />382```383384Lastly, you will define the `handleClick` function inside the `Board` component to update the385squares array holding your board's state.386387The `handleClick` function should take the index of the square to update and create a copy of the388`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`389to the square at the specified index (`i`) if is not already filled.390391```jsx {5-10,27}392export default function Board() {393 const squares = useGameStore((state) => state.squares)394 const setSquares = useGameStore((state) => state.setSquares)395396 function handleClick(i) {397 if (squares[i]) return398 const nextSquares = squares.slice()399 nextSquares[i] = 'X'400 setSquares(nextSquares)401 }402403 return (404 <div405 style={{406 display: 'grid',407 gridTemplateColumns: 'repeat(3, 1fr)',408 gridTemplateRows: 'repeat(3, 1fr)',409 width: 'calc(3 * 2.5rem)',410 height: 'calc(3 * 2.5rem)',411 border: '1px solid #999',412 }}413 >414 {squares.map((square, squareIndex) => (415 <Square416 key={squareIndex}417 value={square}418 onSquareClick={() => handleClick(squareIndex)}419 />420 ))}421 </div>422 )423}424```425426> [!IMPORTANT]427> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array428> instead of modifying the existing array.429430### Taking turns431432It's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the433board.434435You'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece436of state to the `useGameStore` hook:437438```jsx {2,12-18}439const useGameStore = create(440 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {441 return {442 setSquares: (nextSquares) => {443 set((state) => ({444 squares:445 typeof nextSquares === 'function'446 ? nextSquares(state.squares)447 : nextSquares,448 }))449 },450 setXIsNext: (nextXIsNext) => {451 set((state) => ({452 xIsNext:453 typeof nextXIsNext === 'function'454 ? nextXIsNext(state.xIsNext)455 : nextXIsNext,456 }))457 },458 }459 }),460)461```462463Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next464and the game's state will be saved. You'll update the Board's `handleClick` function to flip the465value of `xIsNext`:466

docs: fix missing highlight on setXIsNext line in tic-tac-toe tutorial (#3524)Copilotbefore adoption07cee61

line 467why, one step back
467```jsx {2-3,6,11,13}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 468–569why, one step back
468export default function Board() {
469 const xIsNext = useGameStore((state) => state.xIsNext)470 const setXIsNext = useGameStore((state) => state.setXIsNext)471 const squares = useGameStore((state) => state.squares)472 const setSquares = useGameStore((state) => state.setSquares)473 const player = xIsNext ? 'X' : 'O'474475 function handleClick(i) {476 if (squares[i]) return477 const nextSquares = squares.slice()478 nextSquares[i] = player479 setSquares(nextSquares)480 setXIsNext(!xIsNext)481 }482483 return (484 <div485 style={{486 display: 'grid',487 gridTemplateColumns: 'repeat(3, 1fr)',488 gridTemplateRows: 'repeat(3, 1fr)',489 width: 'calc(3 * 2.5rem)',490 height: 'calc(3 * 2.5rem)',491 border: '1px solid #999',492 }}493 >494 {squares.map((square, squareIndex) => (495 <Square496 key={squareIndex}497 value={square}498 onSquareClick={() => handleClick(squareIndex)}499 />500 ))}501 </div>502 )503}504```505506### Declaring a winner or draw507508Now that the players can take turns, you'll want to show when the game is won or drawn and there509are no more turns to make. To do this you'll add three helper functions. The first helper function510called `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,511`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the512same array, checks for remaining turns by filtering out only `null` items, and returns the count of513them. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the514current player (`'X' or 'O'`):515516```js517function calculateWinner(squares) {518 const lines = [519 [0, 1, 2],520 [3, 4, 5],521 [6, 7, 8],522 [0, 3, 6],523 [1, 4, 7],524 [2, 5, 8],525 [0, 4, 8],526 [2, 4, 6],527 ]528529 for (let i = 0; i < lines.length; i++) {530 const [a, b, c] = lines[i]531 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {532 return squares[a]533 }534 }535536 return null537}538539function calculateTurns(squares) {540 return squares.filter((square) => !square).length541}542543function calculateStatus(winner, turns, player) {544 if (!winner && !turns) return 'Draw'545 if (winner) return `Winner ${winner}`546 return `Next player: ${player}`547}548```549550You will use the result of `calculateWinner(squares)` in the Board component's `handleClick`551function to check if a player has won. You can perform this check at the same time you check if a552user has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in553both cases:554555```js {2}556function handleClick(i) {557 if (squares[i] || winner) return558 const nextSquares = squares.slice()559 nextSquares[i] = player560 setSquares(nextSquares)561 setXIsNext(!xIsNext)562}563```564565To let the players know when the game is over, you can display text such as `'Winner: X'` or566`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will567display the winner or draw if the game is over and if the game is ongoing you'll display which568player's turn is next:569

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

line 570why, one step back
570```jsx {6-7,9,20-21,40}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 571–948why, one step back
571export default function Board() {
572 const xIsNext = useGameStore((state) => state.xIsNext)573 const setXIsNext = useGameStore((state) => state.setXIsNext)574 const squares = useGameStore((state) => state.squares)575 const setSquares = useGameStore((state) => state.setSquares)576 const winner = calculateWinner(squares)577 const turns = calculateTurns(squares)578 const player = xIsNext ? 'X' : 'O'579 const status = calculateStatus(winner, turns, player)580581 function handleClick(i) {582 if (squares[i] || winner) return583 const nextSquares = squares.slice()584 nextSquares[i] = player585 setSquares(nextSquares)586 setXIsNext(!xIsNext)587 }588589 return (590 <>591 <div style={{ marginBottom: '0.5rem' }}>{status}</div>592 <div593 style={{594 display: 'grid',595 gridTemplateColumns: 'repeat(3, 1fr)',596 gridTemplateRows: 'repeat(3, 1fr)',597 width: 'calc(3 * 2.5rem)',598 height: 'calc(3 * 2.5rem)',599 border: '1px solid #999',600 }}601 >602 {squares.map((square, squareIndex) => (603 <Square604 key={squareIndex}605 value={square}606 onSquareClick={() => handleClick(squareIndex)}607 />608 ))}609 </div>610 </>611 )612}613```614615Congratulations! You now have a working tic-tac-toe game. And you've just learned the basics of616React and Zustand too. So you are the real winner here. Here is what the code should look like:617618```jsx619import { create } from 'zustand'620import { combine } from 'zustand/middleware'621622const useGameStore = create(623 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {624 return {625 setSquares: (nextSquares) => {626 set((state) => ({627 squares:628 typeof nextSquares === 'function'629 ? nextSquares(state.squares)630 : nextSquares,631 }))632 },633 setXIsNext: (nextXIsNext) => {634 set((state) => ({635 xIsNext:636 typeof nextXIsNext === 'function'637 ? nextXIsNext(state.xIsNext)638 : nextXIsNext,639 }))640 },641 }642 }),643)644645function Square({ value, onSquareClick }) {646 return (647 <button648 style={{649 display: 'inline-flex',650 alignItems: 'center',651 justifyContent: 'center',652 padding: 0,653 backgroundColor: '#fff',654 border: '1px solid #999',655 outline: 0,656 borderRadius: 0,657 fontSize: '1rem',658 fontWeight: 'bold',659 }}660 onClick={onSquareClick}661 >662 {value}663 </button>664 )665}666667export default function Board() {668 const xIsNext = useGameStore((state) => state.xIsNext)669 const setXIsNext = useGameStore((state) => state.setXIsNext)670 const squares = useGameStore((state) => state.squares)671 const setSquares = useGameStore((state) => state.setSquares)672 const winner = calculateWinner(squares)673 const turns = calculateTurns(squares)674 const player = xIsNext ? 'X' : 'O'675 const status = calculateStatus(winner, turns, player)676677 function handleClick(i) {678 if (squares[i] || winner) return679 const nextSquares = squares.slice()680 nextSquares[i] = player681 setSquares(nextSquares)682 setXIsNext(!xIsNext)683 }684685 return (686 <>687 <div style={{ marginBottom: '0.5rem' }}>{status}</div>688 <div689 style={{690 display: 'grid',691 gridTemplateColumns: 'repeat(3, 1fr)',692 gridTemplateRows: 'repeat(3, 1fr)',693 width: 'calc(3 * 2.5rem)',694 height: 'calc(3 * 2.5rem)',695 border: '1px solid #999',696 }}697 >698 {squares.map((square, squareIndex) => (699 <Square700 key={squareIndex}701 value={square}702 onSquareClick={() => handleClick(squareIndex)}703 />704 ))}705 </div>706 </>707 )708}709710function calculateWinner(squares) {711 const lines = [712 [0, 1, 2],713 [3, 4, 5],714 [6, 7, 8],715 [0, 3, 6],716 [1, 4, 7],717 [2, 5, 8],718 [0, 4, 8],719 [2, 4, 6],720 ]721722 for (let i = 0; i < lines.length; i++) {723 const [a, b, c] = lines[i]724 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {725 return squares[a]726 }727 }728729 return null730}731732function calculateTurns(squares) {733 return squares.filter((square) => !square).length734}735736function calculateStatus(winner, turns, player) {737 if (!winner && !turns) return 'Draw'738 if (winner) return `Winner ${winner}`739 return `Next player: ${player}`740}741```742743### Adding time travel744745As a final exercise, let's make it possible to “go back in time” and revisit previous moves in the746game.747748If you had directly modified the squares array, implementing this time-travel feature would be very749difficult. However, since you used `slice()` to create a new copy of the squares array after every750move, treating it as immutable, you can store every past version of the squares array and navigate751between them.752753You'll keep track of these past squares arrays in a new state variable called `history`. This754`history` array will store all board states, from the first move to the latest one, and will look755something like this:756757```js758const history = [759 // First move760 [null, null, null, null, null, null, null, null, null],761 // Second move762 ['X', null, null, null, null, null, null, null, null],763 // Third move764 ['X', 'O', null, null, null, null, null, null, null],765 // and so on...766]767```768769This approach allows you to easily navigate between different game states and implement the770time-travel feature.771772### Lifting state up, again773774Next, you will create a new top-level component called `Game` to display a list of past moves. This775is where you will store the `history` state that contains the entire game history.776777By placing the `history` state in the `Game` component, you can remove the `squares` state from the778`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`779component. This change allows the `Game` component to have full control over the `Board`'s780component data and instruct the `Board` component to render previous turns from the `history`.781782First, add a `Game` component with `export default` and remove it from `Board` component. Here is783what the code should look like:784785```jsx {1,44-61}786function Board() {787 const xIsNext = useGameStore((state) => state.xIsNext)788 const setXIsNext = useGameStore((state) => state.setXIsNext)789 const squares = useGameStore((state) => state.squares)790 const setSquares = useGameStore((state) => state.setSquares)791 const winner = calculateWinner(squares)792 const turns = calculateTurns(squares)793 const player = xIsNext ? 'X' : 'O'794 const status = calculateStatus(winner, turns, player)795796 function handleClick(i) {797 if (squares[i] || winner) return798 const nextSquares = squares.slice()799 nextSquares[i] = player800 setSquares(nextSquares)801 setXIsNext(!xIsNext)802 }803804 return (805 <>806 <div style={{ marginBottom: '0.5rem' }}>{status}</div>807 <div808 style={{809 display: 'grid',810 gridTemplateColumns: 'repeat(3, 1fr)',811 gridTemplateRows: 'repeat(3, 1fr)',812 width: 'calc(3 * 2.5rem)',813 height: 'calc(3 * 2.5rem)',814 border: '1px solid #999',815 }}816 >817 {squares.map((square, squareIndex) => (818 <Square819 key={squareIndex}820 value={square}821 onSquareClick={() => handleClick(squareIndex)}822 />823 ))}824 </div>825 </>826 )827}828829export default function Game() {830 return (831 <div832 style={{833 display: 'flex',834 flexDirection: 'row',835 fontFamily: 'monospace',836 }}837 >838 <div>839 <Board />840 </div>841 <div style={{ marginLeft: '1rem' }}>842 <ol>{/* TODO */}</ol>843 </div>844 </div>845 )846}847```848849Add some state to the `useGameStore` hook to track the history of moves:850851```js {2,4-11}852const useGameStore = create(853 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {854 return {855 setHistory: (nextHistory) => {856 set((state) => ({857 history:858 typeof nextHistory === 'function'859 ? nextHistory(state.history)860 : nextHistory,861 }))862 },863 setXIsNext: (nextXIsNext) => {864 set((state) => ({865 xIsNext:866 typeof nextXIsNext === 'function'867 ? nextXIsNext(state.xIsNext)868 : nextXIsNext,869 }))870 },871 }872 }),873)874```875876Notice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of8779 null values.878879To render the squares for the current move, you'll need to read the most recent squares array from880the `history` state. You don't need an extra state for this because you already have enough881information to calculate it during rendering:882883```jsx {2-6}884export default function Game() {885 const history = useGameStore((state) => state.history)886 const setHistory = useGameStore((state) => state.setHistory)887 const xIsNext = useGameStore((state) => state.xIsNext)888 const setXIsNext = useGameStore((state) => state.setXIsNext)889 const currentSquares = history[history.length - 1]890891 return (892 <div893 style={{894 display: 'flex',895 flexDirection: 'row',896 fontFamily: 'monospace',897 }}898 >899 <div>900 <Board />901 </div>902 <div style={{ marginLeft: '1rem' }}>903 <ol>{/*TODO*/}</ol>904 </div>905 </div>906 )907}908```909910Next, create a `handlePlay` function inside the `Game` component that will be called by the `Board`911component to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the912`Board` component:913914```jsx {8-10,21}915export default function Game() {916 const history = useGameStore((state) => state.history)917 const setHistory = useGameStore((state) => state.setHistory)918 const xIsNext = useGameStore((state) => state.xIsNext)919 const setXIsNext = useGameStore((state) => state.setXIsNext)920 const currentSquares = history[history.length - 1]921922 function handlePlay(nextSquares) {923 // TODO924 }925926 return (927 <div928 style={{929 display: 'flex',930 flexDirection: 'row',931 fontFamily: 'monospace',932 }}933 >934 <div>935 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />936 </div>937 <div style={{ marginLeft: '1rem' }}>938 <ol>{/*TODO*/}</ol>939 </div>940 </div>941 )942}943```944945Let's make the `Board` component fully controlled by the props it receives. To do this, we'll modify946the `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that947the `Board` component can call with the updated squares array when a player makes a move.948

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

line 949why, one step back
949```jsx {1,11}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 950–1174why, one step back
950function Board({ xIsNext, squares, onPlay }) {
951 const winner = calculateWinner(squares)952 const turns = calculateTurns(squares)953 const player = xIsNext ? 'X' : 'O'954 const status = calculateStatus(winner, turns, player)955956 function handleClick(i) {957 if (squares[i] || winner) return958 const nextSquares = squares.slice()959 nextSquares[i] = player960 onPlay(nextSquares)961 }962963 return (964 <>965 <div style={{ marginBottom: '0.5rem' }}>{status}</div>966 <div967 style={{968 display: 'grid',969 gridTemplateColumns: 'repeat(3, 1fr)',970 gridTemplateRows: 'repeat(3, 1fr)',971 width: 'calc(3 * 2.5rem)',972 height: 'calc(3 * 2.5rem)',973 border: '1px solid #999',974 }}975 >976 {squares.map((square, squareIndex) => (977 <Square978 key={squareIndex}979 value={square}980 onSquareClick={() => handleClick(squareIndex)}981 />982 ))}983 </div>984 </>985 )986}987```988989The `Board` component is now fully controlled by the props passed to it by the `Game` component. To990get the game working again, you need to implement the `handlePlay` function in the `Game`991component.992993What should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with994an updated array; now it passes the updated squares array to `onPlay`.995996The `handlePlay` function needs to update the `Game` component's state to trigger a re-render.997Instead of using `setSquares`, you'll update the `history` state variable by appending the updated998squares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`999component used1000to do.10011002```js {2-3}1003function handlePlay(nextSquares) {1004 setHistory(history.concat([nextSquares]))1005 setXIsNext(!xIsNext)1006}1007```10081009At this point, you've moved the state to live in the `Game` component, and the UI should be fully1010working, just as it was before the refactor. Here is what the code should look like at this point:10111012```jsx1013import { create } from 'zustand'1014import { combine } from 'zustand/middleware'10151016const useGameStore = create(1017 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {1018 return {1019 setHistory: (nextHistory) => {1020 set((state) => ({1021 history:1022 typeof nextHistory === 'function'1023 ? nextHistory(state.history)1024 : nextHistory,1025 }))1026 },1027 setXIsNext: (nextXIsNext) => {1028 set((state) => ({1029 xIsNext:1030 typeof nextXIsNext === 'function'1031 ? nextXIsNext(state.xIsNext)1032 : nextXIsNext,1033 }))1034 },1035 }1036 }),1037)10381039function Square({ value, onSquareClick }) {1040 return (1041 <button1042 style={{1043 display: 'inline-flex',1044 alignItems: 'center',1045 justifyContent: 'center',1046 padding: 0,1047 backgroundColor: '#fff',1048 border: '1px solid #999',1049 outline: 0,1050 borderRadius: 0,1051 fontSize: '1rem',1052 fontWeight: 'bold',1053 }}1054 onClick={onSquareClick}1055 >1056 {value}1057 </button>1058 )1059}10601061function Board({ xIsNext, squares, onPlay }) {1062 const winner = calculateWinner(squares)1063 const turns = calculateTurns(squares)1064 const player = xIsNext ? 'X' : 'O'1065 const status = calculateStatus(winner, turns, player)10661067 function handleClick(i) {1068 if (squares[i] || winner) return1069 const nextSquares = squares.slice()1070 nextSquares[i] = player1071 onPlay(nextSquares)1072 }10731074 return (1075 <>1076 <div style={{ marginBottom: '0.5rem' }}>{status}</div>1077 <div1078 style={{1079 display: 'grid',1080 gridTemplateColumns: 'repeat(3, 1fr)',1081 gridTemplateRows: 'repeat(3, 1fr)',1082 width: 'calc(3 * 2.5rem)',1083 height: 'calc(3 * 2.5rem)',1084 border: '1px solid #999',1085 }}1086 >1087 {squares.map((square, squareIndex) => (1088 <Square1089 key={squareIndex}1090 value={square}1091 onSquareClick={() => handleClick(squareIndex)}1092 />1093 ))}1094 </div>1095 </>1096 )1097}10981099export default function Game() {1100 const history = useGameStore((state) => state.history)1101 const setHistory = useGameStore((state) => state.setHistory)1102 const xIsNext = useGameStore((state) => state.xIsNext)1103 const setXIsNext = useGameStore((state) => state.setXIsNext)1104 const currentSquares = history[history.length - 1]11051106 function handlePlay(nextSquares) {1107 setHistory(history.concat([nextSquares]))1108 setXIsNext(!xIsNext)1109 }11101111 return (1112 <div1113 style={{1114 display: 'flex',1115 flexDirection: 'row',1116 fontFamily: 'monospace',1117 }}1118 >1119 <div>1120 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1121 </div>1122 <div style={{ marginLeft: '1rem' }}>1123 <ol>{/*TODO*/}</ol>1124 </div>1125 </div>1126 )1127}11281129function calculateWinner(squares) {1130 const lines = [1131 [0, 1, 2],1132 [3, 4, 5],1133 [6, 7, 8],1134 [0, 3, 6],1135 [1, 4, 7],1136 [2, 5, 8],1137 [0, 4, 8],1138 [2, 4, 6],1139 ]11401141 for (let i = 0; i < lines.length; i++) {1142 const [a, b, c] = lines[i]1143 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {1144 return squares[a]1145 }1146 }11471148 return null1149}11501151function calculateTurns(squares) {1152 return squares.filter((square) => !square).length1153}11541155function calculateStatus(winner, turns, player) {1156 if (!winner && !turns) return 'Draw'1157 if (winner) return `Winner ${winner}`1158 return `Next player: ${player}`1159}1160```11611162### Showing the past moves11631164Since you are recording the tic-tac-toe game's history, you can now display a list of past moves to1165the player.11661167You already have an array of `history` moves in store, so now you need to transform it to an array1168of React elements. In JavaScript, to transform one array into another, you can use the Array1169`.map()` method:11701171You'll use `map` to transform your `history` of moves into React elements representing buttons on the1172screen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in1173the `Game` component:1174

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

line 1175why, one step back
1175```jsx {13-15,29-44}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1176–1296why, one step back
1176export default function Game() {
1177 const history = useGameStore((state) => state.history)1178 const setHistory = useGameStore((state) => state.setHistory)1179 const xIsNext = useGameStore((state) => state.xIsNext)1180 const setXIsNext = useGameStore((state) => state.setXIsNext)1181 const currentSquares = history[history.length - 1]11821183 function handlePlay(nextSquares) {1184 setHistory(history.concat([nextSquares]))1185 setXIsNext(!xIsNext)1186 }11871188 function jumpTo(nextMove) {1189 // TODO1190 }11911192 return (1193 <div1194 style={{1195 display: 'flex',1196 flexDirection: 'row',1197 fontFamily: 'monospace',1198 }}1199 >1200 <div>1201 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1202 </div>1203 <div style={{ marginLeft: '1rem' }}>1204 <ol>1205 {history.map((_, historyIndex) => {1206 const description =1207 historyIndex > 01208 ? `Go to move #${historyIndex}`1209 : 'Go to game start'12101211 return (1212 <li key={historyIndex}>1213 <button onClick={() => jumpTo(historyIndex)}>1214 {description}1215 </button>1216 </li>1217 )1218 })}1219 </ol>1220 </div>1221 </div>1222 )1223}1224```12251226Before you can implement the `jumpTo` function, you need the `Game` component to keep track of which1227step the user is currently viewing. To do this, define a new state variable called `currentMove`,1228which will start at `0`:12291230```js {3,14-21}1231const useGameStore = create(1232 combine(1233 { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },1234 (set) => {1235 return {1236 setHistory: (nextHistory) => {1237 set((state) => ({1238 history:1239 typeof nextHistory === 'function'1240 ? nextHistory(state.history)1241 : nextHistory,1242 }))1243 },1244 setCurrentMove: (nextCurrentMove) => {1245 set((state) => ({1246 currentMove:1247 typeof nextCurrentMove === 'function'1248 ? nextCurrentMove(state.currentMove)1249 : nextCurrentMove,1250 }))1251 },1252 setXIsNext: (nextXIsNext) => {1253 set((state) => ({1254 xIsNext:1255 typeof nextXIsNext === 'function'1256 ? nextXIsNext(state.xIsNext)1257 : nextXIsNext,1258 }))1259 },1260 }1261 },1262 ),1263)1264```12651266Next, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll1267also set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.12681269```js {2-3}1270function jumpTo(nextMove) {1271 setCurrentMove(nextMove)1272 setXIsNext(currentMove % 2 === 0)1273}1274```12751276You will now make two changes to the `handlePlay` function in the `Game` component, which is called1277when you click on a square.12781279- If you "go back in time" and then make a new move from that point, you only want to keep the1280 history up to that point. Instead of adding `nextSquares` after all items in the history (using1281 the Array `.concat()` method), you'll add it after all items in1282 `history.slice(0, currentMove + 1)` to keep only that portion of the old history.1283- Each time a move is made, you need to update `currentMove` to point to the latest history entry.12841285```js {2-4}1286function handlePlay(nextSquares) {1287 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1288 setHistory(nextHistory)1289 setCurrentMove(nextHistory.length - 1)1290 setXIsNext(!xIsNext)1291}1292```12931294Finally, you will modify the `Game` component to render the currently selected move, instead of1295always rendering the final move:1296

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

line 1297why, one step back
1297```jsx {4-5,8}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1298–1362why, one step back
1298export default function Game() {
1299 const history = useGameStore((state) => state.history)1300 const setHistory = useGameStore((state) => state.setHistory)1301 const currentMove = useGameStore((state) => state.currentMove)1302 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1303 const xIsNext = useGameStore((state) => state.xIsNext)1304 const setXIsNext = useGameStore((state) => state.setXIsNext)1305 const currentSquares = history[currentMove]13061307 function handlePlay(nextSquares) {1308 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1309 setHistory(nextHistory)1310 setCurrentMove(nextHistory.length - 1)1311 setXIsNext(!xIsNext)1312 }13131314 function jumpTo(nextMove) {1315 setCurrentMove(nextMove)1316 setXIsNext(nextMove % 2 === 0)1317 }13181319 return (1320 <div1321 style={{1322 display: 'flex',1323 flexDirection: 'row',1324 fontFamily: 'monospace',1325 }}1326 >1327 <div>1328 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1329 </div>1330 <div style={{ marginLeft: '1rem' }}>1331 <ol>1332 {history.map((_, historyIndex) => {1333 const description =1334 historyIndex > 01335 ? `Go to move #${historyIndex}`1336 : 'Go to game start'13371338 return (1339 <li key={historyIndex}>1340 <button onClick={() => jumpTo(historyIndex)}>1341 {description}1342 </button>1343 </li>1344 )1345 })}1346 </ol>1347 </div>1348 </div>1349 )1350}1351```13521353### Final cleanup13541355If you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and1356`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can1357always determine what `xIsNext` should be.13581359There's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state1360because it can reduce bugs and make your code easier to understand. Instead, you can calculate1361`xIsNext` based on `currentMove`:1362

docs: fix missing code highlights in tic-tac-toe tutorial (#3527)Copilotbefore adoptiona1f685c

line 1363why, one step back
1363```jsx {6,13,17}

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1364–1429why, one step back
1364export default function Game() {
1365 const history = useGameStore((state) => state.history)1366 const setHistory = useGameStore((state) => state.setHistory)1367 const currentMove = useGameStore((state) => state.currentMove)1368 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1369 const xIsNext = currentMove % 2 === 01370 const currentSquares = history[currentMove]13711372 function handlePlay(nextSquares) {1373 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1374 setHistory(nextHistory)1375 setCurrentMove(nextHistory.length - 1)1376 }13771378 function jumpTo(nextMove) {1379 setCurrentMove(nextMove)1380 }13811382 return (1383 <div1384 style={{1385 display: 'flex',1386 flexDirection: 'row',1387 fontFamily: 'monospace',1388 }}1389 >1390 <div>1391 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1392 </div>1393 <div style={{ marginLeft: '1rem' }}>1394 <ol>1395 {history.map((_, historyIndex) => {1396 const description =1397 historyIndex > 01398 ? `Go to move #${historyIndex}`1399 : 'Go to game start'14001401 return (1402 <li key={historyIndex}>1403 <button onClick={() => jumpTo(historyIndex)}>1404 {description}1405 </button>1406 </li>1407 )1408 })}1409 </ol>1410 </div>1411 </div>1412 )1413}1414```14151416You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no1417chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding1418the components.14191420### Wrapping up14211422Congratulations! You’ve created a tic-tac-toe game that:14231424- Lets you play tic-tac-toe,1425- Indicates when a player has won the game or when is drawn,1426- Stores a game’s history as a game progresses,1427- Allows players to review a game’s history and see previous versions of a game’s board.14281429Nice work! We hope you now feel like you have a decent grasp of how React and Zustand works.