Skip to content

No way to cancel animation state updates on an unmounted component #434

@kirbysayshi

Description

@kirbysayshi

Bug Report

Describe the Bug

There appears to be no canceling of the animation when the component unmounts. onFinished will still fire, even if the component has been removed from the DOM by React. The internals of use-web-animation also perform state updates during the animation cycle, which causes a warning from react.

How to Reproduce

  1. Go to the code sandbox link below
  2. Watch the console
  3. After 2 seconds you will see the typical react error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
JustWaitAnim@https://zzit3.csb.app/src/App.js:27:58

I've traced this into the code, and I believe the warning originates from checking then setting the animation state:

if (prevPlayStateRef.current !== curPlayState)
setPlayState(curPlayState);
.

CodeSandbox Link

Codesandbox link: https://codesandbox.io/s/use-web-animations-no-state-unmounted-component-bug-zzit3?file=/src/App.js

Expected Behavior

Personally, I didn't expect the onFinish callback to fire if unmounted! But I understand why it does. Mostly, I don't think the hook should trigger React warnings.

I see a few possibilities:

  1. prevent checking for animation state if the component unmounts
  2. cancel animations when the component unmounts (a new feature? canceling animations seems non-trivial to prevent thrown exceptions: https://developer.mozilla.org/en-US/docs/Web/API/Animation/cancel#exceptions)
  3. provide a flag option (autocancel?) that will call animation.cancel(), as well as cancel any checking and callback execution.

I ran into this bug because I was controlling the autoplay option with a component property. This actually resulted in the animation running twice! It took me several hours before I found the issue: use-web-animations uses these values to know whether to apply the animation. Thus, it assumed that it was a new animation configuration and should be applied. I was using the onFinish callbacks to trigger logic updates, which caused many bugs due to firing twice!

Additional Information

Thank you for making use-web-animations! I think it's a really neat library!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions