Skip to content

Instantly share code, notes, and snippets.

@dagda1
Last active January 27, 2019 17:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dagda1/79dd983ae61e1b8d6bb19ad7cb35ce9b to your computer and use it in GitHub Desktop.
Save dagda1/79dd983ae61e1b8d6bb19ad7cb35ce9b to your computer and use it in GitHub Desktop.
import { EasingName, easing } from './easingMap';
import { useLayoutEffect, useState, useRef } from 'react';
export interface AnimationIncreaseProps {
easingName?: EasingName;
duration?: number;
diff: number;
}
export const useIncreaseAnimation = ({
easingName = EasingName.linear,
diff: end,
duration = 500
}: AnimationIncreaseProps) => {
const [increase, setIncrease] = useState(0);
const start = useRef<number>(null);
useLayoutEffect(() => {
let raf: number;
const frame = (timestamp: number) => {
if (!start.current) {
(start as any).current = timestamp;
}
if (!start.current) {
throw new Error('no start');
}
const time = timestamp - start.current;
const percentRange = Math.min(time / duration, 1);
const percent = easing[easingName as string](percentRange);
setIncrease(increase + end * percent);
if (time < duration) {
raf = requestAnimationFrame(frame);
}
};
raf = requestAnimationFrame(frame);
return () => {
cancelAnimationFrame(raf);
};
}, [end]);
return increase;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment