---
tags: 110-2
---
# 3/4 部課 : React Advanced
## Hooks: [start!](https://reactjs.org/docs/hooks-intro.html)
>Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
## Lets give it a try!
```javascript=
import React, { useState } from "react";
function Square({ value, onClick }) {
return (
<button className="square" onClick={onClick}>
{value}
</button>
);
}
function Board() {
const [squares, setSquares] = useState(Array(9).fill(null));
const [currentPlayer, setCurrentPlayer] = useState("X");
const handleClick = (i) => {
if (calculateWinner(squares)) {
return;
}
if (squares[i] === null) {
let new_squares = squares.slice(); // copy
new_squares[i] = currentPlayer;
setSquares(new_squares);
if (currentPlayer === "O") setCurrentPlayer("X");
else setCurrentPlayer("O");
}
};
const handleRestart = () => {
setSquares(Array(9).fill(null));
setCurrentPlayer("X");
};
const renderSquare = (i) => {
return <Square value={squares[i]} onClick={() => handleClick(i)} />;
};
const winner = calculateWinner(squares);
let status;
if (winner) {
status = `Winner: ${winner}`;
} else {
status = currentPlayer === "X" ? "Next player: X" : "Next player: O";
}
return (
<div>
<div>
<div className="status">{status}</div>
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
<div>
<button onClick={handleRestart}>Restart</button>
</div>
</div>
</div>
);
}
const Game = () => {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info"></div>
</div>
);
};
function calculateWinner(squares) {
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],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
export default Game;
```