how to call a function after completion of setting of group of state variables of functional component in reactjs

Viewed 13
function check(){
const [variable, setvariable1] = useState(0);
const [variable2, setvariable2] = useState(0);
const [variable3, setvariable3] = useState(0);

const last_func = () => {
console.log("call this function")
}

const mainfunction = () =>{
setvariable(1);
setvariable2(1);
setvariable3(1);
last_func(); //this function needs to be called after completing above all state variables
}
}

i want call the last_func after completing the setting of all state variables to 1 then only i have to call that last_func

1 Answers
const mainfunction = () =>{
 setvariable(1);
 setvariable2(1);
 setvariable3(1);

 if(variable !== 0 && variable2 !== 0 && variable3 !== 0) last_func()

 //or if you know that variables will be equal to 1
 if(variable === 1 && variable2 === 1 && variable3 === 1) last_func()
}

also if you want to run last_fun automatically after all variables are >0 you can use useEffect:

useEffect(()=>{
mainfunction();
}, [variable, variable2, variable3])
Related