Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 1x | import { FC, useEffect, useState } from "react";
export interface CountUpProps {
end: number;
start?: number;
duration?: number; // seconds
className?: string;
}
/**
* requestAnimationFrame count from `start` to `end`. `run` gates when it begins
* (used by CountUpOnDisplay to defer until scrolled into view).
*
* Hand-rolled on purpose: the previous react-countup / react-visibility-sensor
* deps are CJS and their default imports resolve to module objects in the rollup
* production build (React error #130), while working in the Vite dev server.
*/
export function useCount(
start: number,
end: number,
durationSec: number,
run: boolean,
): number {
const [value, setValue] = useState(start);
useEffect(() => {
if (!run) return;
const ms = Math.max(durationSec, 0.01) * 1000;
const t0 = performance.now();
let raf = 0;
const tick = (now: number) => {
const p = Math.min((now - t0) / ms, 1);
setValue(Math.round(start + (end - start) * p));
if (p < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [start, end, durationSec, run]);
return value;
}
export const CountUp: FC<CountUpProps> = ({
end,
start = 0,
duration = 2,
className,
}) => {
const value = useCount(start, end, duration, true);
return <span className={className}>{value}</span>;
};
|