AnimatedCounter restarted from 0 on every online-count cache refresh (~10s) because the effect depended on value. Rewrote it as a single requestAnimationFrame animation with ease-out; changes to value after the animation only update the display statically.
58 lines
1.2 KiB
TypeScript
58 lines
1.2 KiB
TypeScript
"use client";
|
|
|
|
import { motion, useInView } from "motion/react";
|
|
import { useEffect, useRef, useState } from "react";
|
|
|
|
export function AnimatedCounter({
|
|
value,
|
|
suffix = "",
|
|
}: {
|
|
value: number;
|
|
suffix?: string;
|
|
}) {
|
|
const ref = useRef<HTMLSpanElement>(null);
|
|
const isInView = useInView(ref, { once: true, margin: "-50px" });
|
|
const started = useRef(false);
|
|
const [display, setDisplay] = useState(0);
|
|
|
|
useEffect(() => {
|
|
if (!isInView) return;
|
|
|
|
if (started.current) {
|
|
setDisplay(value);
|
|
return;
|
|
}
|
|
started.current = true;
|
|
|
|
const duration = 1200;
|
|
const start = performance.now();
|
|
let raf = 0;
|
|
|
|
const tick = (now: number) => {
|
|
const progress = Math.min((now - start) / duration, 1);
|
|
const eased = 1 - (1 - progress) ** 3;
|
|
setDisplay(Math.round(eased * value));
|
|
if (progress < 1) {
|
|
raf = requestAnimationFrame(tick);
|
|
} else {
|
|
setDisplay(value);
|
|
}
|
|
};
|
|
|
|
raf = requestAnimationFrame(tick);
|
|
return () => cancelAnimationFrame(raf);
|
|
}, [isInView, value]);
|
|
|
|
return (
|
|
<motion.span
|
|
ref={ref}
|
|
initial={{ opacity: 0, y: 12 }}
|
|
animate={isInView ? { opacity: 1, y: 0 } : {}}
|
|
transition={{ duration: 0.5, ease: "easeOut" }}
|
|
>
|
|
{display.toLocaleString()}
|
|
{suffix}
|
|
</motion.span>
|
|
);
|
|
}
|