Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

878 B
Raw Blame
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 }];
};