Skip to content

Instantly share code, notes, and snippets.

@librz
Created December 29, 2022 10:12
Show Gist options
  • Save librz/9947f4b5e09a8a038a15f6d5022514e8 to your computer and use it in GitHub Desktop.
Save librz/9947f4b5e09a8a038a15f6d5022514e8 to your computer and use it in GitHub Desktop.
Proof React's setState is asynchronous
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