Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
React state management - Rerenders with useEffect

Ok so to explain my problem in short. I was following a rock-paper-scissors tutorial, but when I finished it, I started implementing stuff on my own. I am not new to React, but I also have a lot to learn still. I want to completely understand state management. A quick explanation:

This is a rock-paper-scissors game, where the user can click on buttons which represent the rock, paper and scissors, and the same button that gets the user input, also generates random computer choice from those 3. (handleClick func)

I then have a useEffect that compares the user and computer choice, and then increase user or computer points by 1, to whoever won that round. When the points from either one of them reach 5, the game ends and a restart button shows up.

And now my problem:

When I add the conditional logic in the useEffect that sees if anyone of them reached 5 points, my click is always 1 behind. Im setting a state for the game over, which is false on the app load, and gets set to true, when the condition is met. So in this case it will reach 5, but the restart button itself is gonna show up on the next click.

BUT, if I add the logic to the JSX instead, without using state, the restart button shows on round 5 exactly, which is the correct way.

Now, I researched quite a lot, and I know that setState is async, and it will be evaluated on the next render.. but I don’t get why it does that if I put it in the useEffect, which also has the dependency array, which will trigger a rerender if the state changes. Even when I put the 'gameOver' in the dependacy array, it still doesnt work

I am missing some key info to put the whole puzzle in place.

You can find the code here, its not very long.

https://www.codepile.net/pile/6PO6m8GN

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

if you want to trigger a rerender, you can use dependency array of useEffect. So, if you want to trigger useEffect when computer or user point changes, add them inside your useEffect dependency array.

This guy explains it perfectly: https://www.youtube.com/watch?v=dH6i3GurZW8&t=1106s

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda