Search code examples
react-nativereact-animated

Should I explicitly stop React Native animations on unmount?


Suppose I'm starting an animation with Animated.timing().start(), doesn't matter when exactly (on mount, or on some external event). Then I'm using an Animated.View to render the animation.

Suppose it does not complete before the component unmounts.

Should I explicitly call stop() on the animation (and indeed, all animations that could still be running) on unmount, or will it get cleaned up implicitly? Most manually allocated resources don't get implicitly deallocated (unless they're attached to the component, like hooks), but it seems like animations do.


Solution

  • I didn't find any documentation about this, but I had a look through the code of the version we're using (0.59.8).

    The short answer is no, there is no need to stop animations explicitly, it is managed by React Native.

    The long answer follows my code analysis below.

    • When you start an animation for a certain value, that animation is bound to the Animated.Value. (either as _animation, or as _tracking.)

    • When you use the Animated.Value on an Animated.Component, the value is attached to the component as _propsAnimated.

    • On componentWillUnmount _propsAnimated is __detached, and __detach on the Animated.Value stops the animation by calling Animated.Value.prototype.stopAnimation (which is a public function of Animated.Value).