Skip to content

Instantly share code, notes, and snippets.

@SuperJony
Forked from malerba118/use-clock.ts
Created June 15, 2024 20:37
Show Gist options
  • Save SuperJony/03a33e8ffc10f84f97c73266ab5994c5 to your computer and use it in GitHub Desktop.
Save SuperJony/03a33e8ffc10f84f97c73266ab5994c5 to your computer and use it in GitHub Desktop.
import {
MotionValue,
useAnimationFrame,
useMotionValue,
} from "framer-motion";
import React from "react";
export interface Clock {
value: MotionValue<number>;
setRate: (rate: number) => void;
}
export const useClock = ({ defaultValue = 0, rate = 1 } = {}): Clock => {
const value = useMotionValue(defaultValue);
const rateRef = React.useRef(rate);
useAnimationFrame((_, delta) => {
value.set(value.get() + delta * rateRef.current);
});
return {
value,
setRate: (rate: number) => {
rateRef.current = rate;
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment