stellar
stellar

Reputation: 33

Why result of state update is reacting in 2 different ways

I have created a simple TicTacToe using react-hooks.

  1. Sometimes I am getting result before my state update is shown on screen.

enter image description here

  1. Sometimes it is showing result after update is shown on screen.

enter image description here

I am not getting why it is reacting in 2 different ways.

Please find the code link below.

playground link

Upvotes: 0

Views: 70

Answers (2)

Nader Alfakesh
Nader Alfakesh

Reputation: 201

alert() function is blocking function so when alert window opens your app is on pause until user hit ok button.

alert function can sometimes race with rendering, that's why sometimes the alert shows before the last render and your app on pause so you will not see the change on the grid.

it happens when you The solution is to replace alert() whith another visual element such as modals

Upvotes: 2

Enes Ceylan
Enes Ceylan

Reputation: 114

Issue probably comes from your useState, you can try adding dependency array for the useState with player change so it only checks the game after each round.

From:

useEffect(() => {
  CheckGame();
});

To:

useEffect(() => {
  CheckGame();
}, [player]);

Upvotes: 0

Related Questions