Files
ThreadNet-Web/src/hooks/useTimeoutToggle.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

43 lines
1.0 KiB
TypeScript
Raw Normal View History

2022-11-22 07:58:37 +01:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
2022-11-22 07:58:37 +01:00
Copyright 2022 The Matrix.org Foundation C.I.C.
2024-09-09 14:57:16 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
2022-11-22 07:58:37 +01:00
*/
import { useEffect, useRef, useState } from "react";
/**
* Hook that allows toggling a boolean value and resets it after a timeout.
*
* @param {boolean} defaultValue Default value
* @param {number} timeoutMs Time after that the value will be reset
*/
export const useTimeoutToggle = (
defaultValue: boolean,
timeoutMs: number,
): {
value: boolean;
toggle(): void;
} => {
2022-11-22 07:58:37 +01:00
const timeoutId = useRef<number | undefined>();
const [value, setValue] = useState<boolean>(defaultValue);
const toggle = (): void => {
2022-11-22 07:58:37 +01:00
setValue(!defaultValue);
2022-11-30 11:32:56 +00:00
timeoutId.current = window.setTimeout(() => setValue(defaultValue), timeoutMs);
2022-11-22 07:58:37 +01:00
};
useEffect(() => {
return () => {
clearTimeout(timeoutId.current);
};
});
return {
toggle,
value,
};
};