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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With