@ybiquitous/use-toggle

React useToggle() utility hook

Usage no npm install needed!

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

README

useToggle()

npm

React useToggle() utility hook.

  • React 16.8+
  • No dependencies
  • TypeScript support

Install

npm install @ybiquitous/use-toggle

Usage

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

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

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

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

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

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]);