Be careful about that code snippet regarding useState update function.
useState
// index is 10 ... setIndex(index + 1) // next iteration index = 11 (...) setIndex(index + 1) // next iteration index = 11
But if you read the documentation about functional updates then you'll have to use a callback to grab the latest value.
This is important whenever you're updating a state using the previous state for calculations.
// index is 10 ... setIndex((index) => index + 1) // next iteration index = 11 (...) setIndex((index) => index + 1) // next iteration index = 12
Thanks! I actually have seen it both ways and was confused about why they both work so that is really helpful
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Be careful about that code snippet regarding
useState
update function.But if you read the documentation about functional updates then you'll have to use a callback to grab the latest value.
This is important whenever you're updating a state using the previous state for calculations.
Thanks! I actually have seen it both ways and was confused about why they both work so that is really helpful