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) ?
>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.