0

I am learning hooks. I am trying to update state but it's not reflecting immediately. Here is my code.

const Test = (props) => {
    const [score , setScore] = useState(0);
    const [count , setCount] = useState(0);
    const [total, setTotal] = useState(0);
 
const playerBallClick= ()=> {
        setCount(count+1);
        setScore(Math.floor(Math.random() * 10));
        setTotal(total + score);
    }

return (
        <div>
            <button onClick={playerBallClick}>Ball</button>
    {/* <p>Total score is - {totalscore}</p> */}
        </div>
    )
}

How can I update Total immediately onclick on Ball button.

Anurag Mishra
  • 647
  • 3
  • 15
  • 31
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – jonrsharpe Sep 22 '20 at 09:35

2 Answers2

2

Score is a stale closure try the following instead:

const playerBallClick = () => {
  setCount(count + 1);
  const newScore = Math.floor(Math.random() * 10);
  setScore(newScore);
  setTotal(total => total + newScore);
};
HMR
  • 37,593
  • 24
  • 91
  • 160
2

You can use useEffect hook like so,

useEffect(() => {
   setTotal(total + score);
}, [count]);

So everytime count state changes, this hook will be called updating your total state.