React Checkbox Pro

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

import { useCheckbox } from 'react-checkbox-pro';
 
function CustomCheckbox() {
  const checkboxProps = useCheckbox({
    defaultChecked: true,
    onChange: (checked) => console.log(checked),
    disabled: false
  });
 
  return (
    <input
      type="checkbox"
      {...checkboxProps}
    />
  );
}

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

PropTypeDefault
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

PropTypeDefault
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

function ControlledCheckbox() {
  const [checked, setChecked] = useState(false);
  const checkboxProps = useCheckbox({
    checked,
    onChange: setChecked
  });
 
  return (
    <input
      type="checkbox"
      {...checkboxProps}
    />
  );
}

With Event Handler

function EventHandlerCheckbox() {
  const checkboxProps = useCheckbox({
    onChange: (event) => {
      console.log('Checked:', event.target.checked);
    }
  });
 
  return (
    <input
      type="checkbox"
      {...checkboxProps}
    />
  );
}

With Indeterminate State

function IndeterminateCheckbox() {
  const checkboxProps = useCheckbox({
    indeterminate: true,
    onChange: (checked) => console.log('Checked:', checked)
  });
 
  return (
    <input
      type="checkbox"
      {...checkboxProps}
    />
  );
}

Best Practices

  1. State Management:

    • Choose between controlled and uncontrolled based on your needs
    • Use appropriate onChange handler type
    • Consider form integration requirements
  2. Error Handling:

    • Handle validation states
    • Provide error messages
    • Maintain accessibility during errors
  3. Performance:

    • Memoize callbacks when needed
    • Avoid unnecessary re-renders
    • Use proper dependency arrays
  4. Accessibility:

    • Provide proper ARIA attributes
    • Handle keyboard interactions
    • Test with screen readers

Resources

On this page