Why is the setPoints((prevPoint) => prevPoint + 1) in useEffect
keeps adding 2 times almost immediately?
I’ve tried everything, how do I best fix this for it to print only once?
I am trying to check if the moving animation have gotten to a certain distance which is the value of distanceOfScreenTopToBigCircle
, so I can add one to the point state, but it keeps adding 1 two times almost immediately.
const theBallPosition = new Animated.ValueXY({x: 0, y: 0});
const destinationY = distanceOfScreenTopToBigCircle ? distanceOfScreenTopToBigCircle : 0;
function movingBallFunction() {
//const destinationY = ballAtTop ? distanceOfScreenTopToBigCircle : 0;
//This is linear animation
Animated.timing(theBallPosition, {
toValue: {x: 0, y: destinationY},//This the distance the ball should fall to
duration: movingBallTimeDuration,//This is for the time the ball should reach the bigCircle
easing: Easing.linear,
useNativeDriver: true,
}).start();//This start() method starts our animation
//This is to not show the instruction on how to start game when user
//have started playing the game, or when the ball is moving already. .
setShowHowToStartGameInstruction(false)
}
useEffect(() => {
const animationListener = (value) => {
if (value.y === distanceOfScreenTopToBigCircle) {
console.log('it has reach the finals,', value.y)
return setPoints((prevPoint) => prevPoint + 1);
}
};
// Attach the listener
const listenerId = theBallPosition.addListener(animationListener);
// Cleanup mechanism: remove the listener when the component unmounts
return () => {
theBallPosition.removeListener(listenerId);
};
}, [theBallPosition, distanceOfScreenTopToBigCircle])
2
Answers
This is due to the changes that React introduced with React v18. This is intentional by the React developers and is supposed to help catch hard to spot bugs during your development.
It happens when running in Strict Mode and is development only…essentially your component is unmounted and re-mounted automatically after the initial mounting.
Here’s the React Blog’s announcement for React v18: https://react.dev/blog/2022/03/29/react-v18#new-strict-mode-behaviors
And here’s an article about possibly fixing it: https://medium.com/@arm.ninoyan/fixed-react-18-useeffect-runs-twice-8480f0bd837f
This is a duplicate question for why does use effect render twice
Please make sure to search your questions and make sure there are no existing answers before asking them in the future!