Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React changes the state only if button is clicked twice

I’m a beginner with react and when I’m using useState to change name of the button, it does not work as intended.
Specifically: when I’m pushing the button it’s name "Unclicked" must change to "Clicked" and when I push it again it should change back to "Unclicked" and so on. In reality, when I click the button it changes to "Clicked" in one click but to change it back, the button must be pushed twice.

My code

the result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Well, I’m expecting the button to change it’s name on only one click.

>Solution :

You are wrongly using clicked variable. it will be reset to 0 every time component re-renders.

change to

if(buttonName === 'Unclicked')
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading