React debouncer hook (without deps)

Date: 2024-02-09
export function useDebounce(callback: (...args: any[]) => any, delay: number) {
    const timeoutRef = useRef<any>(null);

    useEffect(() => {
        // Cleanup the previous timeout on re-render
        return () => {
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
            }
        };
    }, []);

    const debouncedCallback = (...args: any[]) => {
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
        }

        timeoutRef.current = setTimeout(() => {
            callback(...args);
        }, delay);
    };

    return debouncedCallback;
};

function SearchBox(props: { onSearch: (searchText: string) => any }) {
    const { onSearch } = props;

    const debouncedSearch = useDebounce(onSearch, 500);
    return <Input.Search placeholder={translate("filter-search-placeholder")} onChange={(e) => debouncedSearch(e.target.value)} onSearch={onSearch} />
}

82540cookie-checkReact debouncer hook (without deps)