What happens if I call Animated.timing() after the component has been unmounted?

20 Views Asked by At

From what I could find out, when an animated component unmounts it will be end all the ongoing animations associated with them. What happens if inside the onFinish callbacks of this animations we trigger another animation (like Animated.timing) ? Will react native ignore the stop/ignore the animation right away, or will this lead to a memory leak.

For example


const App = () => {
  const [isVisible, setIsVisible] = useState(true);
  useEffect(() => {
    let interval = setInterval(() => {
       setIsVisible((vis) => !vis);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  return isVisible ? <AnimatedComponent /> : null;
}

const AnimatedComponent = () => {
  const [state, setState] = useState(true);
  const viewOpacity = useRef(new Animated.Value(0));
  const fadeIn = useCallback(() => {
    viewOpacity.setValue(0);
    Animated.timing(viewOpacity, {
      toValue: 1,
      duration: 3000,
      useNativeDriver: true,
    }).start(() => {
      setTimeout(fadeOut, 5000);
    });
  }, []);

  const fadeOut = useCallback(() => {
    viewOpacity.setValue(1);
    Animated.timing(viewOpacity, {
      toValue: 0,
      duration: 3000,
      useNativeDriver: true,
    }).start(() => setState(false));
  }, []);

  useEffect(() => {
    fadeIn();
  }, []);

  
  return <Animated.View style={{opacity: viewOpacity.current}}></Animated.Value>
}

I once identified a memory leak in my app, where there was a similar situation, if we take the example of above code, instead of calling fadeOut inside the onFinish callback of fadeIn, it called fadeIn recursively. It lead to a "Excessive number of pending callbacks" warning after a few mounts, and the app became unresponsive.

Will this code lead to a similar situation over multiple mounts?

Also After the unmount, lets say fadeOut was a complex animation, will the entire calculation be executed, or the onFinish callback for it be called instantly.

0

There are 0 best solutions below