mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-14 19:44:52 +00:00
41 lines
878 B
TypeScript
41 lines
878 B
TypeScript
import { useCallback, useState } from "react";
|
|
|
|
type VoidFn = () => void;
|
|
|
|
type UseToggleReturn = [
|
|
boolean,
|
|
{
|
|
on: VoidFn;
|
|
off: VoidFn;
|
|
toggle: VoidFn;
|
|
timedToggle: (timeout?: number) => void;
|
|
}
|
|
];
|
|
|
|
export const useToggle = (initialState = false): UseToggleReturn => {
|
|
const [value, setValue] = useState(initialState);
|
|
|
|
const on = useCallback(() => {
|
|
setValue(true);
|
|
}, []);
|
|
|
|
const off = useCallback(() => {
|
|
setValue(false);
|
|
}, []);
|
|
|
|
const toggle = useCallback((isOpen?: boolean) => {
|
|
setValue((prev) => (typeof isOpen === "boolean" ? isOpen : !prev));
|
|
}, []);
|
|
|
|
const timedToggle = useCallback((timeout = 2000) => {
|
|
setValue((prev) => !prev);
|
|
|
|
const timeoutRef = setTimeout(() => {
|
|
setValue(false);
|
|
clearTimeout(timeoutRef);
|
|
}, timeout);
|
|
}, []);
|
|
|
|
return [value, { on, off, toggle, timedToggle }];
|
|
};
|