Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/hooks/use-temporary-value.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 { useCallback, useEffect, useRef, useState } from "react";
8
9
type UseTemporaryStateReturnType<ValueType> = [value: ValueType, set: (value: ValueType) => void];
10
11
/**
12
* @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.
13
*
14
* @param defaultValue Default value
15
* @param timeout Milliseconds to revert to default value after setting a temporary value
16
* @returns [value, setTemporaryValue]
17
*/
18
export const useTemporaryState = <ValueType>(
19
defaultValue: ValueType,
20
timeout: number,
21
): UseTemporaryStateReturnType<ValueType> => {
22
const [value, setValue] = useState<ValueType>(defaultValue);
23
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
24
25
const setTemporaryValue = useCallback(
26
(tempValue: ValueType, revertValue?: ValueType) => {
27
timeoutRef.current && clearTimeout(timeoutRef.current);
28
29
setValue(tempValue);
30
31
timeoutRef.current = setTimeout(() => {
32
setValue(revertValue !== undefined ? revertValue : defaultValue);
33
}, timeout);
34
},
35
[defaultValue, timeout],
36
);
37
38
useEffect(() => {
39
if (timeoutRef.current) {
40
clearTimeout(timeoutRef.current);
41
}
42
}, []);
43
44
return [value, setTemporaryValue];
45
};
46
47