useCheckbox
A powerful hook for managing checkbox state and behavior
useCheckbox Hook
The useCheckbox
hook provides a flexible way to manage checkbox state and behavior in your React components. It handles both controlled and uncontrolled modes, different onChange patterns, and manages accessibility attributes.
Basic Usage
Features
State Management
Handles both controlled and uncontrolled checkbox states
Event Handling
Supports both boolean and event-based onChange handlers
Accessibility
Manages ARIA attributes for better accessibility
Type Safety
Full TypeScript support with proper type definitions
API Reference
Hook Parameters
Prop | Type | Default |
---|---|---|
checked | boolean | - |
defaultChecked | boolean | - |
onChange | ((checked: boolean) => void) | ((event: ChangeEvent<HTMLInputElement>) => void) | - |
disabled | boolean | - |
required | boolean | - |
name | string | - |
value | string | - |
indeterminate | boolean | - |
aria-label | string | - |
aria-labelledby | string | - |
aria-describedby | string | - |
aria-invalid | boolean | - |
Return Value
Prop | Type | Default |
---|---|---|
checked | boolean | - |
onChange | (event: ChangeEvent<HTMLInputElement>) => void | - |
disabled | boolean | - |
required | boolean | - |
name | string | - |
value | string | - |
aria-checked | boolean | "mixed" | - |
aria-invalid | boolean | - |
ref | RefObject<HTMLInputElement> | - |
Examples
Controlled Mode
With Event Handler
With Indeterminate State
Best Practices
-
State Management:
- Choose between controlled and uncontrolled based on your needs
- Use appropriate onChange handler type
- Consider form integration requirements
-
Error Handling:
- Handle validation states
- Provide error messages
- Maintain accessibility during errors
-
Performance:
- Memoize callbacks when needed
- Avoid unnecessary re-renders
- Use proper dependency arrays
-
Accessibility:
- Provide proper ARIA attributes
- Handle keyboard interactions
- Test with screen readers