Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/hooks/use-debounce.ts
2500 views
1
/**
2
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { useEffect, useMemo, useState } from "react";
8
import debounce from "lodash/debounce";
9
10
type DebounceOptions = {
11
leading?: boolean;
12
trailing?: boolean;
13
maxWait?: number;
14
};
15
16
export const useDebounce = <T>(value: T, delay = 500, options?: DebounceOptions): T => {
17
const [debouncedValue, setDebouncedValue] = useState<T>(value);
18
19
const debouncedSetValue = useMemo(() => {
20
return debounce(setDebouncedValue, delay, {
21
leading: options?.leading || false,
22
trailing: options?.trailing || true,
23
// ensures debounced value is updated at least every 1s
24
maxWait: options?.maxWait ?? 1000,
25
});
26
}, [delay, options?.leading, options?.maxWait, options?.trailing]);
27
28
useEffect(() => {
29
debouncedSetValue(value);
30
}, [value, debouncedSetValue]);
31
32
return debouncedValue;
33
};
34
35