React Checkbox Pro

Controlled Checkbox

How to use React Checkbox Pro in controlled mode

Controlled Checkbox

Learn how to use React Checkbox Pro in controlled mode, where you manage the checkbox state in your React component.

Example

Current state: Unchecked

Usage

Basic Controlled Mode

function ControlledCheckbox() {
  const [checked, setChecked] = useState(false);
 
  return (
    <Checkbox 
      checked={checked}
      onChange={setChecked}
    >
      Controlled Checkbox
    </Checkbox>
  );
}

With Custom Handler

function ControlledWithHandler() {
  const [checked, setChecked] = useState(false);
 
  const handleChange = (newChecked: boolean) => {
    console.log('Checkbox state:', newChecked);
    setChecked(newChecked);
  };
 
  return (
    <Checkbox 
      checked={checked}
      onChange={handleChange}
    >
      With Custom Handler
    </Checkbox>
  );
}

Best Practices

  1. Use controlled mode when you need to:

    • Sync checkbox state with other components
    • Validate state changes
    • Perform side effects on state changes
  2. Always provide both checked and onChange props

  3. Consider using useCallback for performance optimization:

    const handleChange = useCallback((checked: boolean) => {
      setChecked(checked);
    }, []);
  4. Avoid unnecessary re-renders by keeping state management close to where it's needed

On this page