Skip to content

Commit 370fd5e

Browse files
authored
Performance: Fix slow color picker (#1969)
* Fix Performance issue when picking color Signed-off-by: Moulik Aggarwal <qwertymoulik@gmail.com> * Fix any type in hook Signed-off-by: Moulik Aggarwal <qwertymoulik@gmail.com> * Theme sidebar handleChange Signed-off-by: Moulik Aggarwal <qwertymoulik@gmail.com> --------- Signed-off-by: Moulik Aggarwal <qwertymoulik@gmail.com>
1 parent 40ac0ee commit 370fd5e

File tree

2 files changed

+42
-9
lines changed

2 files changed

+42
-9
lines changed

apps/status-page/src/components/themes/theme-sidebar.tsx

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
} from "@openstatus/ui/components/ui/tooltip";
4848
import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";
4949
import { useDebounce } from "@openstatus/ui/hooks/use-debounce";
50+
import { useDebounceCallback } from "@openstatus/ui/hooks/use-debounce-callback";
5051
import { cn } from "@openstatus/ui/lib/utils";
5152
import {
5253
Check,
@@ -344,6 +345,17 @@ function ThemeValueSelector(props: {
344345
}) {
345346
const { resolvedTheme } = useTheme();
346347

348+
const handleChange = useDebounceCallback((value: string) => {
349+
const mode = resolvedTheme as "light" | "dark";
350+
props.setTheme({
351+
...props.theme,
352+
[mode]: {
353+
...props.theme[mode],
354+
[props.id]: value,
355+
},
356+
});
357+
}, 100);
358+
347359
if (!props.isMounted || !resolvedTheme)
348360
return <Skeleton className="ml-auto size-4 border border-foreground/70" />;
349361

@@ -362,15 +374,7 @@ function ThemeValueSelector(props: {
362374
name={props.id}
363375
value={value}
364376
className="sr-only"
365-
onChange={(e) =>
366-
props.setTheme({
367-
...props.theme,
368-
[resolvedTheme as "light" | "dark"]: {
369-
...props.theme[resolvedTheme as "light" | "dark"],
370-
[props.id]: e.target.value,
371-
},
372-
})
373-
}
377+
onChange={(e) => handleChange(e.target.value)}
374378
/>
375379
</label>
376380
);
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { useCallback, useEffect, useRef } from "react";
2+
3+
export function useDebounceCallback<Args extends unknown[]>(
4+
callback: (...args: Args) => void,
5+
delay = 500,
6+
) {
7+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
8+
9+
const debounced = useCallback(
10+
(...args: Args) => {
11+
if (timerRef.current) {
12+
clearTimeout(timerRef.current);
13+
}
14+
15+
timerRef.current = setTimeout(() => {
16+
callback(...args);
17+
}, delay);
18+
},
19+
[callback, delay],
20+
);
21+
22+
useEffect(() => {
23+
return () => {
24+
if (timerRef.current) clearTimeout(timerRef.current);
25+
};
26+
}, []);
27+
28+
return debounced;
29+
}

0 commit comments

Comments
 (0)