-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathanimated-counter.tsx
More file actions
53 lines (43 loc) · 1.18 KB
/
animated-counter.tsx
File metadata and controls
53 lines (43 loc) · 1.18 KB
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
51
52
53
"use client";
import { useEffect, useState } from "react";
interface UseAnimatedCounterProps {
value: number;
duration?: number;
}
export const useAnimatedCounter = ({
value,
duration = 2000,
}: UseAnimatedCounterProps) => {
const [displayValue, setDisplayValue] = useState(0);
useEffect(() => {
const startTime = Date.now();
const startValue = 0;
const animate = () => {
const now = Date.now();
const elapsed = now - startTime;
const progress = Math.min(elapsed / duration, 1);
// Easing function for smooth animation
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
const currentValue = Math.round(
startValue + (value - startValue) * easeOutQuart,
);
setDisplayValue(currentValue);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}, [value, duration]);
return displayValue;
};
// Animated Counter Component
export const AnimatedCounter = ({
value,
duration = 2000,
}: {
value: number;
duration?: number;
}) => {
const displayValue = useAnimatedCounter({ value, duration });
return <span>{displayValue.toLocaleString()}</span>;
};