OneCompiler

Unable to update Boolean state in react

I've a Boolean state clicked that is used to show the value of a switch.
Whenever the user presses the switch the opposite of current state should become the new state. I tried like below

<button onClick = {()=> setClicked(!clicked) } />

But it is not working as expected. How can I make it work like i expected?

1 Answer

5 years ago by

You need to get the previous state first and update it.
You can do like

setClicked( prev => !prev)
5 years ago by Divya