Created
April 21, 2021 21:31
-
-
Save richleach/2f6f4473daeb3c06454abc2c2d302e82 to your computer and use it in GitHub Desktop.
In React you need to use previous state during incrementing loops because React doesn't apply state updates immediately due to performance, so if you're expecting to update state and then immediately see it, you should ask Santa for it instead.
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
function HookCounter() { | |
const [count, setCount] = useState(initialCount) | |
//why you need prevState | |
const incrementFive = () => { | |
for(let i=0; i <5; i++){ | |
setCount(prevCount => prevCount + 1) | |
} | |
} | |
return ( | |
<div> | |
<button onClick = {() => setCount(prevCount => prevCount + 1)}>Increment</button> | |
</div> | |
) | |
} | |
export default HookCounter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment