Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/hooks/use-state-with-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
export const useStateWithDebounce = <T>(initialValue: T, delay = 500): [T, (value: T) => void, T] => {
11
const [value, setValue] = useState<T>(initialValue);
12
const [debouncedValue, setDebouncedValue] = useState<T>(initialValue);
13
14
const debouncedSetValue = useMemo(() => {
15
return debounce(setDebouncedValue, delay);
16
}, [delay]);
17
18
useEffect(() => {
19
debouncedSetValue(value);
20
}, [value, debouncedSetValue]);
21
22
return [value, setValue, debouncedValue];
23
};
24
25