Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React state not updated inside event handler

I have a state variable that determines whether a button is rendered. The onclick handler of the button toggles the state and is supposed to remove the button. But the state never gets updated inside the event handler (works fine in Safari by the power of God). All other function calls work fine. But the state never gets updated, not even with a delay (checked in devtools). It looks something like..

const [shown, setShown] = useState(true)

return (
  shown ? (
    <button
      onClick={(ev) => {
        console.log(shown) // outputs true
        setShown(false) // does absolutely nothing, no errors
        console.log(shown) // outputs true
      }}
    ></button>
  ) : (
    <OtherElement />
  )
)

This is a simplified version I guess. I 'solved' this by changing onClick to

onClick={ () => 
  setTimeout(
    setShown.bind(undefined, false)
  ,0)
}

I'm not sure if this is ideal or not. Any ideas?

like image 687
thurasw Avatar asked May 12 '26 21:05

thurasw


1 Answers

This is because React batches the setState try having a handler funcion and add a useEffect like this

useEffect(()=>{ console.log("Shown Chnaged") },[shown])

when you are setting state it doesn't immediately re-render because of React's batching mechanism

Refer to this article for more

like image 166
Sachin Ananthakumar Avatar answered May 15 '26 10:05

Sachin Ananthakumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!