Path: blob/main/components/dashboard/src/hooks/use-state-with-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";89export const useStateWithDebounce = <T>(initialValue: T, delay = 500): [T, (value: T) => void, T] => {10const [value, setValue] = useState<T>(initialValue);11const [debouncedValue, setDebouncedValue] = useState<T>(initialValue);1213const debouncedSetValue = useMemo(() => {14return debounce(setDebouncedValue, delay);15}, [delay]);1617useEffect(() => {18debouncedSetValue(value);19}, [value, debouncedSetValue]);2021return [value, setValue, debouncedValue];22};232425