Goal: Make toggle logic so clear, it reads like plain English.
“What really matters is how well your code communicates to the people who are going to read it later.” — Kent C. Dodds (Fixate Podcast)
TL;DR: A hook to standardize toggle verbs
& states
in React.
Define nouns - myModal
or myCheckbox
instead of isMyModalOpen
or isMyCheckboxChecked
.
Invoke verbs - open
, close
, toggle
, etc. to change a noun’s state - open(myModal)
.
Read state - via noun.state
- like myModal.isOpen
import useToggles, { open, toggle } from 'toggles' // **standerd verbs:** open/close/toggle **(+/-/♾️)**
const { sidebar, custom } = useToggles() // create your own **custom toggle nouns**
open(sidebar) // updates all +states to true (isOpen/isOn/etc.)
sidebar.isOpen === true // **standerd states:** isOpen/isClosed **(+/-)**
yarn add toggles
npm i -S toggles
verb(noun)
+ noun.state
After examining a laundry list of common UI elements a pattern emerged:
verb(noun)
→ the action you’d naturally speak → check(checkbox)
noun.state
→ a simple boolean: is it on or off → checkbox.isChecked
That is exactly what useToggles codifies through a growing dictionary of +verbs (on)
, -verbs (off)
, and a universal ♾️verb (toggle)
. By leveraging useToggles
and useToggle
hooks, we can unify naming across our application, so every UI element’s behavior feels natural and consistent.
import useToggles, { useToggle, open, close, toggle } from 'toggles'
function App() {
// Multiple local toggles
const { modal, sidebar } = useToggles(false, true)
// Single toggle (can be global with namespace string)
const darkMode = useToggle('darkMode-namespace', false)
return (
<>
<button onClick={() => open(modal)}>Open Modal</button>
<button onClick={() => toggle(sidebar)}>Toggle Sidebar</button>
<button onClick={() => toggle(darkMode)}>Toggle Dark Mode</button>
<div className={darkMode.isOn ? 'dark' : 'light'}>
{modal.isOpen && <Modal onClose={() => close(modal)} />}
{sidebar.isVisible && <Sidebar />}
</div>
</>
)
}
const nouns = useToggles(...defaultState[]?)