Skip to content

Hooks + animations = how? #14195

@Karolusrex

Description

@Karolusrex

Do you want to request a feature or report a bug?

I doubt it's a bug, so it's either a missing feature or a request for clarification on how to use/not to use hooks.

What is the current behavior?

I'm trying to design an interactive component with animation event listeners. As highlighted by this issue, state updates behave differently when triggered from events than from other sources. In this case I want to use requestAnimationFrame to incrementally update a value using a setter function.

This is my best effort so far (after a lot of tinkering):

const useAnimationFrame = callback => {
  let isDisplaying = true;
  const loop = () => {
    if (!isDisplaying) {
      return;
    }
    callback();
    requestAnimationFrame(loop);
  };
  useEffect(() => {
    requestAnimationFrame(loop);
    return () => {
      isDisplaying = false;
    };
  });
};

It sort of works, but I'm not sure it's ideal. Here's the fiddle: https://codesandbox.io/s/0y609q54pw. Is this really how I'm supposed to be doing it? I use this approach in a complex component (an image carousel) and the performance is noticably worse than the this.setState traditional approach counterpart.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions