React useToggle() utility hook

Usage no npm install needed!

<script type="module">
  import ybiquitousUseToggle from 'https://cdn.skypack.dev/@ybiquitous/use-toggle';




React useToggle() utility hook.

  • React 16.8+
  • No dependencies
  • TypeScript support


npm install @ybiquitous/use-toggle


import useToggle from "@ybiquitous/use-toggle";

function Check() {
  const [checked, check, uncheck, toggle] = useToggle();

  return (
      <input type="checkbox" checked={checked} onChange={toggle} />
      <button onClick={check}>Check</button>
      <button onClick={uncheck}>Uncheck</button>

function Show() {
  const [isShown, show, hide] = useToggle();

  return (
      <button onClick={show}>Show</button>
      <button onClick={hide}>Hide</button>
      {isShown && <strong>Hello</strong>}

See also the online demo!

Why not useState()

This utility hook aims to reduce the following boilerplate with useState():

function App() {
  const [isShown, setShown] = useState(false);
  const toggle = setShown((state) => !state);
  const show = () => setShown(true);
  const hide = () => setShown(false);

  const showButton = <button onClick={show}>Show</button>;
  const hideButton = <button onClick={hide}>Hide</button>;

  // ...

In addition, this package benefits performance by useCallback(). This means that it is equivalent to:

const show = useCallback(() => setShown(true), [setShown]);