DEV Community

Discussion on: React: Using State in Functional Components

Collapse
 
tiagojpdias profile image
Tiago Dias

Be careful about that code snippet regarding useState update function.

// index is 10
...
setIndex(index + 1) // next iteration index = 11
(...)
setIndex(index + 1) // next iteration index = 11
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
austinbrownopspark profile image
Austin Brown • Edited

Thanks! I actually have seen it both ways and was confused about why they both work so that is really helpful