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 : How to call setState twice if the second relies on the first?

How do I achieve this simple logic in react if the second setState hook depends on thee first one to change first?
In this example, the first setState value doesn’t update fast enough before running the second setState.
I have tried putting the second one in a timeout, as well as putting it inside a callback function of the first. Didn’t work out.
The useEffect might solve this issue but in this particular instance I would need to call useEffect only in the first one and not every time there is a state change. Let me know your thoughts.

function blah(arg) {
    if (condition) {
        setState(arg)
    }
    setState(state + 1)
}

>Solution :

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

React’s State isn’t meant to work as a variable. When you call setState, you are simply telling the code what value it is supposed to use in the next rendering of the component. It will never set the value immediatly.

If you need it to behave as a variable, just use variables and call setState a single time at the end.

function blah(arg) {
    let aux = state;
    if (condition) {
        aux = arg;
    }
    setState(aux + 1);
}
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