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

Is setState doing something when passing the state current value?

I have a (minor) performance question : when passing the current value of a state to its setState, is it doing something ?

In my case, on a user action, I want to update a boolean state to true only if its current value is false. Is it better to do :
!myState && setMyState(true) or simply setMyState(true) ?

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

>Solution :

Based on my experience, setting the same state using the useState hook does not retrigger hooks or rerendering. The primary purpose of useState is to manage state and control its side effects. This optimisation is certainly implemented by the React team, as a simple check to determine if the state has changed prevents unnecessary re-renders.

Another consideration is that prechecking the state before updating is not the best idea is that it could lead to code that is harder to be understood by other developers reviewing it. Performance optimisation might not be the initial assumption upon encountering such code. Instead, concerns might arise about the state not being a boolean or changing unpredictably. It’s important to prioritise code clarity and predictability alongside performance optimisations.

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