@ybiquitous/use-toggle
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

useToggle()

npm

React useToggle() hook, which makes it easy to handle a togglable (boolean) state.

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

Readme

Keywords

Package Sidebar

Install

npm i @ybiquitous/use-toggle

Weekly Downloads

0

Version

0.1.1

License

MIT

Unpacked Size

8.02 kB

Total Files

5

Last publish

Collaborators

  • ybiquitous