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 :

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);
}

Leave a Reply