Path: blob/main/components/dashboard/src/hooks/use-debounce.ts
2500 views
/**1* Copyright (c) 2023 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56import { useEffect, useMemo, useState } from "react";7import debounce from "lodash/debounce";89type DebounceOptions = {10leading?: boolean;11trailing?: boolean;12maxWait?: number;13};1415export const useDebounce = <T>(value: T, delay = 500, options?: DebounceOptions): T => {16const [debouncedValue, setDebouncedValue] = useState<T>(value);1718const debouncedSetValue = useMemo(() => {19return debounce(setDebouncedValue, delay, {20leading: options?.leading || false,21trailing: options?.trailing || true,22// ensures debounced value is updated at least every 1s23maxWait: options?.maxWait ?? 1000,24});25}, [delay, options?.leading, options?.maxWait, options?.trailing]);2627useEffect(() => {28debouncedSetValue(value);29}, [value, debouncedSetValue]);3031return debouncedValue;32};333435