0

I want to increase a counter, it's working but not in first calling...

        const [count, setCount] = useState(0)
          function handleClick(){
            setCount(count+5)
            console.log(count)
          }

when I call for first time the function, it should shows "5" directly because I wrote console.log after the increase but in first calling, it shows 0... after (second click) it shows 5... I dont understand

younes
  • 21
  • 3

1 Answers1

0

Correct, it's because the update isn't applied yet in this render. You are updating the state value and trying to access the same value in one render, that won't work. See this answer also.

If you are looking to do something based on the state's new value, you can use the useEffect hook.

const [count, setCount] = useState(0)
function handleClick(){
   setCount(count+5)
}
useEffect(() => {
   console.log(count)
}, [count])
youssef
  • 11
  • 3