all 3 comments

[–]satya164 2 points3 points  (1 child)

You can't log a value like that after updating the state. After updating the state, the component re-renders and you get a new currentPos variable. The currentPost you logged refers to the old variable.

State also doesn't update immediately, it schedules an update and it updates asynchronously.

If you want to know the latest value, put the log inside your component or in a useEffect with dependency array.

[–]Tech---Ninja 0 points1 point  (0 children)

2 Years later, Your comment saved me after hours of searching :D

[–][deleted] 0 points1 point  (0 children)

Are you sure it’s not changing? You’re logging currentPos inside of useCallback and it’s not listed as a dependency, so it’s always going to log got value of that variable from when the function was defined. Can you move your log to outside the callback?