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.
Dark Mode
Installation
Install the useToggle hook using:
File Structure
Parameters
Prop | Type | Default |
---|---|---|
initialValue | boolean | false |
Return Value
Prop | Type | Default |
---|---|---|
value | boolean | - |
toggle | (value?: boolean) => void | - |
Examples
Multiple Toggles Example
Use the hook for multiple toggleable elements:
Dark Mode
Currently inactive
Content is visible
Not in favorites
Accordion Implementation
Create an accordion component with the useToggle hook:
Form Password Visibility
Toggle password visibility in a form:
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:
Benefits include:
- More Concise: Less code to toggle a value
- More Intuitive: Clear intent with a named
toggle
function - More Flexible: Can both toggle and set specific values with the same function
- 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:
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
, oraria-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