8
Hooks

useToggle

A hook that simplifies boolean state management with a single function to toggle state.

useToggle

The useToggle hook provides a simple way to manage boolean state in React components. It’s perfect for implementing toggles, switches, accordions, and any other UI element that has an on/off state.

Simple Toggle

Dark Mode

Installation

Install the useToggle hook using:

npx axionjs-ui add hook use-toggle

File Structure

use-toggle.ts

Parameters

PropTypeDefault
initialValue
boolean
false

Return Value

PropTypeDefault
value
boolean
-
toggle
(value?: boolean) => void
-

Examples

Multiple Toggles Example

Use the hook for multiple toggleable elements:

Simple Toggle

Dark Mode

Multiple Toggles

Currently inactive

Content is visible

Not in favorites

Accordion Implementation

Create an accordion component with the useToggle hook:

FAQ

Form Password Visibility

Toggle password visibility in a form:

function PasswordInput() {
  const [passwordVisible, togglePasswordVisible] = useToggle(false);
  const [password, setPassword] = useState("");
  
  return (
    <div className="password-field">
      <label htmlFor="password">Password</label>
      
      <div className="input-with-button">
        <input
          id="password"
          type={passwordVisible ? "text" : "password"}
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        
        <button
          type="button"
          onClick={() => togglePasswordVisible()}
          aria-label={passwordVisible ? "Hide password" : "Show password"}
        >
          {passwordVisible ? "Hide" : "Show"}
        </button>
      </div>
    </div>
  );
}

Use Cases

  • Toggle Buttons: Simple on/off buttons
  • Switches: UI switches for settings
  • Checkboxes: Toggle checked/unchecked state
  • Modal/Dialog Visibility: Show/hide modals
  • Accordions: Expand/collapse sections
  • Menu Visibility: Toggle dropdown menus
  • Feature Flags: Enable/disable features
  • Theme Switching: Toggle between light/dark mode
  • Password Visibility: Show/hide password in forms
  • Details Disclosure: Show/hide additional details

Benefits

Compared to Plain useState

Using useToggle instead of plain useState for boolean values provides several benefits:

// With useState
const [isOpen, setIsOpen] = useState(false);
 
// To toggle:
setIsOpen(!isOpen);
 
// To set to specific value:
setIsOpen(true);
// With useToggle
const [isOpen, toggle] = useToggle(false);
 
// To toggle:
toggle();
 
// To set to specific value:
toggle(true);

Benefits include:

  1. More Concise: Less code to toggle a value
  2. More Intuitive: Clear intent with a named toggle function
  3. More Flexible: Can both toggle and set specific values with the same function
  4. More Reusable: Standardized pattern for all boolean toggles in your app

Toggle Groups

For managing mutually exclusive toggles, you can combine useToggle with other state:

function TabGroup() {
  const tabs = ["Account", "Security", "Notifications"];
  const [activeTab, setActiveTab] = useState("Account");
  
  return (
    <div className="tabs">
      {tabs.map(tab => (
        <button
          key={tab}
          className={activeTab === tab ? "active" : ""}
          onClick={() => setActiveTab(tab)}
        >
          {tab}
        </button>
      ))}
      
      <div className="tab-content">
        {/* Content for each tab */}
      </div>
    </div>
  );
}

Accessibility

When implementing toggles with this hook, consider these accessibility best practices:

  • Use semantic HTML elements (buttons, checkboxes) for toggle controls
  • Include proper ARIA attributes like aria-expanded, aria-checked, or aria-pressed
  • Ensure keyboard navigation works correctly
  • Provide clear visual indication of the current state
  • Include descriptive labels for screen readers

Best Practices

  • Use a clear naming convention for your toggle state variables (e.g., isVisible, isOpen, hasError)
  • Add appropriate TypeScript types for better code completion and error checking
  • Consider creating composed hooks for specific toggle use cases in your application
  • Use the option to directly set values (toggle(true)) when you need deterministic behavior
  • For complex toggle groups, consider a reducer pattern instead of multiple useToggle instances

On this page