I ran into an issue where some logic within useEffect runs on mount once before a state update within it is triggered. Example below:
function App() {
const [account, setAccount] = useState("0x123");
useEffect(() => {
async function main() {
let fetchedAccount = await //some fetch logic to get new account
setAccount(fetchedAccount);
}
console.log(account);
let result = await someFunction(account);
}
I realized when running this, my App runs the logic with the predefined state i.e. someFunction("0x123") before running someFunction("updated state from fetchedAccount"). So console.log(account) shows "0x123" once and then once more for the fetchedAccount string.
How can I avoid this behavior and just have the useEffect run someFunction(accounts) after setAccount(fetchedAccount) is done?
Previously when it was a class component, I used this.setState to update the 'account' state and the someFunction(this.state.account) worked correctly. It doesn't run with the predefined state and only runs with the updated value after this.setState.
Thanks in advance!
Try adding another useEffect hook that includes 'account' in the dependency array.
useEffect(() => {
if(account !== "0x123"){
let result = await someFunction(account);
}
}, [account])
This should ensure that someFunction will only run if value of account changes.
edit: hmm, would adding a conditional to check that account is not "0x123" fix your issue?
Also, you could set initial state to undefined.