Why does the setPoints((prevPoint) => prevPoint + 1) in useEffect
keep adding twice almost immediately?
I have tried multiple solutions, how can I adjust this so that it only increments once?
I am attempting to monitor the movement animation to determine if it reaches a specific distance indicated by the value of distanceOfScreenTopToBigCircle
. However, the point state is being incremented twice almost instantly.
const theBallPosition = new Animated.ValueXY({x: 0, y: 0});
const destinationY = distanceOfScreenTopToBigCircle ? distanceOfScreenTopToBigCircle : 0;
function movingBallFunction() {
//const destinationY = ballAtTop ? distanceOfScreenTopToBigCircle : 0;
//This is a linear animation
Animated.timing(theBallPosition, {
toValue: {x: 0, y: destinationY},//This determines the distance the ball should fall
duration: movingBallTimeDuration,//This sets the time for the ball to reach the bigCircle
easing: Easing.linear,
useNativeDriver: true,
}).start();//Initiates the animation
//Hides the instruction on starting the game once the user begins playing or when the ball is already in motion. .
setShowHowToStartGameInstruction(false)
}
useEffect(() => {
const animationListener = (value) => {
if (value.y === distanceOfScreenTopToBigCircle) {
console.log('The ball has reached its final position,', value.y)
return setPoints((prevPoint) => prevPoint + 1);
}
};
// Attaches the listener
const listenerId = theBallPosition.addListener(animationListener);
// Clean up mechanism: removes the listener when the component unmounts
return () => {
theBallPosition.removeListener(listenerId);
};
}, [theBallPosition, distanceOfScreenTopToBigCircle])