Return to site

🔁🪝 USETOGGLE: A TINY REACT HOOK THAT SAVES YOU FROM BOOLEAN BOILERPLATE

· react,programmer

Ever find yourself writing the same useState(true/false) + setX(!x) again and again? 😅

For modals, dropdowns, sidebars, dark mode… a simple useToggle hook keeps your components clean and expressive ✅

🔸 TLDR 🧠

A useToggle hook is a tiny custom hook that standardizes boolean toggling, reduces repetition, and makes UI state changes more readable.

Section image

🔸 THE HOOK (SIMPLE + REUSABLE)

import { useState } from "react";

export const useToggle = (initial = false) => {

const [state, set] = useState(initial);

return [state, () => set((s) => !s)];

};

🔸 WHY IT’S USEFUL

▪️ One-liner toggle behavior (no repeated setOpen(o => !o) everywhere)

▪️ Clear intent: toggle() reads better than “invert state” logic

▪️ Easy to reuse across the whole codebase 🧩

▪️ Perfect for UI visibility flags: isOpen, isDark, isExpanded, etc.

🔸 QUICK EXAMPLE (MODAL / DROPDOWN / SIDEBAR)

const [isOpen, toggleOpen] = useToggle();

Toggle

{isOpen && }

🔸 TAKEAWAYS ✅

▪️ Use it for any boolean UI state (open/close, show/hide, enable/disable)

▪️ Keep components focused on UI, not state-flipping mechanics 🎯

▪️ Small hooks like this improve consistency across teams 👥

▪️ If you need more control later, you can extend it (e.g., setTrue, setFalse, set(value))

#react #javascript #frontend #webdevelopment #hooks #reacthooks #cleanCode #codeQuality #uidesign #softwareengineering