Skip to main content

useAnimation

Use this hook to perform JavaScript animation.

API

function useAnimation(
callback: (percent: number) => void,
options:
| number
| { duration: number; algorithm?: (percent: number) => number }
): [start: () => void, cancel: () => void];

Params:

  • callback: Animation process function. It receives a percent number as the first param.
  • options: Animation duration time or an options object.
    • options.duration: Required animation duration time, in milliseconds.
    • options.algorithm: Optional algorithm function. Animation execution is linear by default, you can specify this option to change the default behavior.

Results:

  • start: Start function.
  • cancel: Cancel function.

Example

import React, { useRef } from "react";
import TweenJS from "@tweenjs/tween.js";
import { useAnimation } from "@lilib/hooks";

function Example() {
const domRef = useRef<HTMLDivElement>(null);
const [start, cancel] = useAnimation(
(percent) => {
if (domRef.current) {
domRef.current.style.width = percent * 100 + "%";
}
},
{
duration: 1000,
algorithm: TweenJS.Easing.Bounce.Out,
}
);

return (
<>
<div>
<button onClick={start}>Start</button>{" "}
<button onClick={cancel}>Cancel</button>
</div>
<div
ref={domRef}
style={{ width: 0, height: 8, marginTop: 8, backgroundColor: "orange" }}
></div>
</>
);
}

export default Example;