Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!