Created
December 29, 2022 10:12
-
-
Save librz/9947f4b5e09a8a038a15f6d5022514e8 to your computer and use it in GitHub Desktop.
Proof React's setState is asynchronous
This file contains hidden or 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 { useState, FC } from "react"; | |
const App: FC = () => { | |
const [number, setNumber] = useState(1); | |
const nextNumber = number + 1; | |
function handleIncrease() { | |
setNumber((num) => num + 1); | |
console.log("current number is", number); // still the old number | |
console.log("next number is", nextNumber); // still the old next number | |
} | |
console.log("render"); | |
return ( | |
<div> | |
<h1> | |
Number: {number}; Next: {nextNumber} | |
</h1> | |
<button onClick={handleIncrease}>Increase</button> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment