Skip to content

Instantly share code, notes, and snippets.

@kivircik-parantez
Created December 30, 2022 22:37
Show Gist options
  • Save kivircik-parantez/566d40cb3ecf6a33de6645fc16c1bbd6 to your computer and use it in GitHub Desktop.
Save kivircik-parantez/566d40cb3ecf6a33de6645fc16c1bbd6 to your computer and use it in GitHub Desktop.
Chains of Computation
function Game() {
const [card, setCard] = useState(null);
const [goldCardCount, setGoldCardCount] = useState(0);
const [round, setRound] = useState(1);
// ✅ Calculate what you can during rendering
const isGameOver = round > 5;
function handlePlaceCard(nextCard) {
if (isGameOver) {
throw Error('Game already ended.');
}
// ✅ Calculate all the next state in the event handler
setCard(nextCard);
if (nextCard.gold) {
if (goldCardCount <= 3) {
setGoldCardCount(goldCardCount + 1);
} else {
setGoldCardCount(0);
setRound(round + 1);
if (round === 5) {
alert('Good game!');
}
}
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment