react-use icon indicating copy to clipboard operation
react-use copied to clipboard

Add useSwitcher hook

Open Ruslan-web955 opened this issue 3 months ago β€’ 5 comments

Add a hook that would simplify working with boolean values

/**
 * @param defaultValue	initial value of the switch. Default {@link false}
 * @example
 *  const [isOpen, turnIsOpenOn, turnIsOpenOff, toggleIsOpen] = useSwitcher();
 */
export declare const useSwitcher: (defaultValue?: boolean) => readonly [boolean, () => void, () => void, () => void];

Ruslan-web955 avatar Sep 26 '25 10:09 Ruslan-web955

Hi, I’d be interested in contributing a PR for this if it’s still available.

Deyi-Chen avatar Sep 27 '25 01:09 Deyi-Chen

What's the difference from useToggle?

xiyaowong avatar Sep 27 '25 15:09 xiyaowong

@xiyaowong useToggle returns only one method toggle whereas useSwitcher returns more options

Ruslan-web955 avatar Oct 27 '25 21:10 Ruslan-web955

@Deyi-Chen it's still available

Ruslan-web955 avatar Oct 27 '25 21:10 Ruslan-web955

ready-made code:


/**
 * Hook switch. Makes working with useState<boolean>
 *
 * @param defaultValue initial value of the switch. Default {@link false}
 * @example
 *  const [isOpen, turnIsOpenOn, turnIsOpenOff, toggleIsOpen] = useSwitcher();
 */
export const useSwitcher = (defaultValue = false) => {
  const [value, setValue] = useState<boolean>(defaultValue)

  const on = useCallback(() => setValue(true), [])
  const off = useCallback(() => setValue(false), [])
  const toggleValue = useCallback(() => setValue(prevValue => !prevValue), [])

  return [value, on, off, toggleValue] as const
}```

Ruslan-web955 avatar Dec 20 '25 19:12 Ruslan-web955