React Native: Animation callback does not access latest state while using hooks

508 views Asked by At

hope you all are having a great day. I'm new to react native animations and ran into a problem. Problem is that I'm updating the state inside Animation callback like this

Animated.timing(position, {
  toValue: {
    x: 500,
    y: 0,
  },
  duration: 250,
  useNativeDriver: false,
}).start(() => {
  setActiveIndex(activeIndex + 1)
});

state is updated but when this animation function is called for the second time it does not get access to latest state. If activeIndex is 0 and it runs for first time activeIndex is updated to 1 but when this animation function is called for second time activeIndex is still 0 and it is still updated to 1 and so on. activeIndex is updated outside this callback this only happens inside the callback.

Any help will be appreciated.

1

There are 1 answers

2
Ian Vasco On BEST ANSWER

Alright, I think that the problem is you are not getting and updated value for the state. Remember that setting the state is an async process and by the time you tell React to get activeIndex it can be stale state.

The recommended way to solve this issue is to use the callback for the setState function, which will get the exact previous value for that state, as follows:

setActiveIndex(prevIndex => prevIndex + 1)