fix: debounce func

This commit is contained in:
Sahaj Jain
2025-04-17 16:34:28 +05:30
parent 865b359baa
commit b6cc2008a2
2 changed files with 23 additions and 11 deletions
+11 -8
View File
@@ -1,4 +1,4 @@
import React, { useState, useCallback, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react";
import { Label } from "@/components/ui/label";
import { ColorPickerProps } from "@/types";
import { debounce } from "@/utils/debounce";
@@ -12,13 +12,9 @@ const ColorPicker = ({ color, onChange, label }: ColorPickerProps) => {
setLocalColor(color);
}, [color]);
// Create debounced onChange handler with useCallback to maintain reference
const debouncedOnChange = useCallback(
(value: string) => {
debounce(() => {
onChange(value);
}, 10)();
},
// Create a stable debounced onChange handler
const debouncedOnChange = useMemo(
() => debounce((value: string) => onChange(value), 20),
[onChange]
);
@@ -28,6 +24,13 @@ const ColorPicker = ({ color, onChange, label }: ColorPickerProps) => {
debouncedOnChange(newColor);
};
// Cleanup debounced function on unmount
useEffect(() => {
return () => {
debouncedOnChange.cancel();
};
}, [debouncedOnChange]);
return (
<div className="mb-3">
<div className="flex items-center justify-between mb-1.5">
+12 -3
View File
@@ -1,10 +1,19 @@
export function debounce(fn: (...args: any[]) => void, delay: number) {
export function debounce<T extends (...args: any[]) => void>(
fn: T,
delay: number
): T & { cancel: () => void } {
let timeoutId: NodeJS.Timeout;
return function (...args: any[]) {
const debounced = function (this: unknown, ...args: Parameters<T>) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
// @ts-expect-error: it works
fn.apply(this, args);
}, delay);
} as T & { cancel: () => void };
debounced.cancel = () => {
clearTimeout(timeoutId);
};
return debounced;
}