juliangarnier / anime

JavaScript animation engine
https://animejs.com
MIT License
50.42k stars 3.68k forks source link

Correct usage w/ React Hooks (React 17 / React 18) #841

Open kevinschaich opened 1 year ago

kevinschaich commented 1 year ago

Spent a few hours on this today & hoping I can save someone else the trouble in the future / perhaps we can improve the docs. I was struggling to replicate even the most basic examples from the website/docs for JavaScript Object targets (not DOM elements) in React without stuff acting weird. My use case was not to move elements around but rather to pass values to subcomponents to animate data (deck.gl in my case).

Things wouldn't move at all or move and then not finish / glitch out / hang. I put together a CodeSandbox with all my attempts. First one doesn't move at all, attempts 2-4 are glitchy, and 5 and 6 work correctly.

So – the minimal example is:

import React, { useEffect, useState } from "react";
import anime from "animejs";

const App = () => {
  const [values, setValues] = useState({ x: 0 });

  useEffect(() => {
    anime({
      targets: values,
      x: 100,
      round: 1,
      easing: "linear",
      direction: "alternate",
      duration: 1000,
      loop: true,
      update: (anim) => setValues({ x: values.x })
    });
  }, []);

  return <div>{values.x}</div>;
};

export default App;

Also on CodeSandbox. Hope it helps!

sarojregmi200 commented 1 year ago

Thanks @kevinschaich, It really helps.

juliangarnier commented 1 year ago

This is great, thanks for sharing this example @kevinschaich. I might add it to the new documentation for V4.