Skip to content

Instantly share code, notes, and snippets.

@richleach
Created April 21, 2021 21:31
Show Gist options
  • Save richleach/2f6f4473daeb3c06454abc2c2d302e82 to your computer and use it in GitHub Desktop.
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.
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