Skip to content

Conversation

@beny25585
Copy link

No description provided.

@ShirYahav ShirYahav requested a review from OfekSagiv December 17, 2025 08:51
Comment on lines 94 to 96
squares[index] = NEXT_PLAYER;
calculateWinner(squares);
setSquares([...squares]);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In React, state should be treated as immutable. When you do squares[index] = ..., you are changing the actual object in memory that React is currently tracking.

Comment on lines 17 to 51
const calculateWinner = (squares: (string | null)[]) => {
if (!squares) return;

if (squares[0] && squares[0] === squares[1] && squares[0] === squares[2]) {
setWinner(true);
return;
}
if (squares[3] && squares[3] === squares[4] && squares[3] === squares[5]) {
setWinner(true);
return;
}
if (squares[6] && squares[6] === squares[7] && squares[6] === squares[8]) {
setWinner(true);
return;
}
if (squares[0] && squares[0] === squares[3] && squares[0] === squares[6]) {
setWinner(true);
return;
}
if (squares[1] && squares[1] === squares[4] && squares[1] === squares[7]) {
setWinner(true);
return;
}
if (squares[2] && squares[2] === squares[5] && squares[2] === squares[8]) {
setWinner(true);
return;
}
if (squares[0] && squares[0] === squares[4] && squares[0] === squares[8]) {
setWinner(true);
return;
}
if (squares[2] && squares[2] === squares[4] && squares[2] === squares[6]) {
setWinner(true);
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Writing out every single if statement for every possible win is prone to typos. It makes the function very long and hard to read at a glance.

Define the winning combinations as an array of arrays (a "Win Map") and loop through them. This follows the DRY principle and makes the code much cleaner.

Array(9).fill(null)
);
const [isXNext, setIsXNext] = useState(true);
const [winner, setWinner] = useState(false);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid redundant state for winner. Since it can be calculated directly from squares during render, deriving it ensures your UI is always in sync with the board and prevents 'syncing' bugs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants