Home > Enterprise >  React state management - Rerenders with useEffect
React state management - Rerenders with useEffect

Time:03-04

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

CodePudding user response:

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

CodePudding user response:

because react state is asynchronous. if you want more infomation, check this doc

  • Related