Skip to content

Commit 99a8c19

Browse files
fix(header): restore github stars count animation without flicker
1 parent 59bc0c9 commit 99a8c19

1 file changed

Lines changed: 11 additions & 6 deletions

File tree

frontend/components/shared/GitHubStarButton.tsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { Star } from 'lucide-react';
44
import { useTranslations } from 'next-intl';
5-
import { useEffect, useState } from 'react';
5+
import { useEffect, useRef, useState } from 'react';
66

77
const STORAGE_KEY = 'github-stars';
88

@@ -22,14 +22,18 @@ export function GitHubStarButton({ className = '' }: GitHubStarButtonProps) {
2222
const t = useTranslations('aria');
2323
const [displayCount, setDisplayCount] = useState(0);
2424
const [finalCount, setFinalCount] = useState<number | null>(null);
25+
const displayCountRef = useRef(displayCount);
2526
const githubUrl = 'https://github.com/DevLoversTeam/devlovers.net';
2627

28+
useEffect(() => {
29+
displayCountRef.current = displayCount;
30+
}, [displayCount]);
31+
2732
useEffect(() => {
2833
const cachedStars = getStoredStars();
2934

3035
if (cachedStars !== null) {
3136
const frame = window.requestAnimationFrame(() => {
32-
setDisplayCount(cachedStars);
3337
setFinalCount(cachedStars);
3438
});
3539

@@ -66,12 +70,13 @@ export function GitHubStarButton({ className = '' }: GitHubStarButtonProps) {
6670
}, []);
6771

6872
useEffect(() => {
69-
if (finalCount === null || finalCount === displayCount) return;
73+
if (finalCount === null || finalCount === displayCountRef.current) return;
7074

7175
const duration = 2000;
7276
const steps = 60;
73-
const increment = finalCount / steps;
74-
let current = 0;
77+
const start = displayCountRef.current;
78+
const increment = Math.max((finalCount - start) / steps, 1);
79+
let current = start;
7580

7681
const timer = setInterval(() => {
7782
current += increment;
@@ -87,7 +92,7 @@ export function GitHubStarButton({ className = '' }: GitHubStarButtonProps) {
8792
}, duration / steps);
8893

8994
return () => clearInterval(timer);
90-
}, [displayCount, finalCount]);
95+
}, [finalCount]);
9196

9297
const formatStarCount = (count: number): string => {
9398
return count.toLocaleString();

0 commit comments

Comments
 (0)