If I have a useEffect like this for example:
useEffect(()=>{
doSomething(varOne, varTwo)
},
[varOne]);
I want this to re-run only when varOne is changed, but when it does, I want it to have the updated value of varTwo as well. It doesn't matter to me if varTwo changes and nothing happens, but when varOne does, it should run with both updated values for that moment.
Is this what I should be expecting? It seems to work this way form tests I've done, but I want to make sure that this is reliable and how I should always expect it to work.
Short Answer ... Yes, even if you only reference varOne
in your useEffect
call, all state related values will have already been updated. In the following example, you will see that both varOne
and varTwo
are updated in a button click, but the effect will read both new values when updating the button text.
export default function App() {
const [varOne, setVarOne] = useState('Initial Var One');
const [varTwo, setVarTwo] = useState('Initial Var Two');
const [buttonText, setButtonText] = useState('');
useEffect(() => {
setButtonText(`${varOne} - ${varTwo}`)
}, [varOne]);
const handleClick = () => {
setVarOne('Var One Changed');
setVarTwo('Var Two Changed');
}
return (
<div className="App">
<button onClick={handleClick}>{buttonText}</button>
</div>
);
}