Path: blob/main/components/dashboard/src/hooks/use-temporary-value.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 { useCallback, useEffect, useRef, useState } from "react";78type UseTemporaryStateReturnType<ValueType> = [value: ValueType, set: (value: ValueType) => void];910/**11* @description Hook to have state that reverts to a default value after a timeout when you update it. Useful for temporarily showing messages or disabling buttons.12*13* @param defaultValue Default value14* @param timeout Milliseconds to revert to default value after setting a temporary value15* @returns [value, setTemporaryValue]16*/17export const useTemporaryState = <ValueType>(18defaultValue: ValueType,19timeout: number,20): UseTemporaryStateReturnType<ValueType> => {21const [value, setValue] = useState<ValueType>(defaultValue);22const timeoutRef = useRef<ReturnType<typeof setTimeout>>();2324const setTemporaryValue = useCallback(25(tempValue: ValueType, revertValue?: ValueType) => {26timeoutRef.current && clearTimeout(timeoutRef.current);2728setValue(tempValue);2930timeoutRef.current = setTimeout(() => {31setValue(revertValue !== undefined ? revertValue : defaultValue);32}, timeout);33},34[defaultValue, timeout],35);3637useEffect(() => {38if (timeoutRef.current) {39clearTimeout(timeoutRef.current);40}41}, []);4243return [value, setTemporaryValue];44};454647