@ybiquitous/use-toggle
v0.1.1
Published
React useToggle() hook
Downloads
6
Readme
useToggle()
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]);