Last active
January 29, 2020 03:22
-
-
Save namoshizun/196f3b20b32844d5cc113b1c5d5eba06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { useState, useEffect } from 'react' | |
function App() { | |
const [count, setCount] = useState(0) | |
// Should print the latest count a render happens | |
console.log(count) | |
useEffect(() => { | |
console.log('In effect') | |
const doStuff = async function () { | |
await new Promise((resolve, reject) => { | |
setTimeout(() => { | |
setCount(count + 1) | |
// To resolve stale closure, we need to pass an closure to setCount to make it explicit that it closes on 'count' | |
// i.e., setCount(count => count + 1) | |
resolve() | |
}, 5000) | |
}) | |
// Should print this after 5 s | |
console.log('Stale closure!') | |
// And then count is set back to an old value (maybe 1). | |
} | |
doStuff() | |
}, []) | |
return <div> | |
<button onClick={() => setCount(count + 1)}> | |
Clicked {count} times | |
</button> | |
</div> | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment