Back to Hooks

useTristate

useTristate.tsx

useTristate

STATE_MGMT

// Manage a 3-valued state (true | false | indeterminate) with cycling helpers

Quick Usage

const { value, setTrue, setFalse, setIndeterminate, cycle } = useTristate(false);

Features

3-Value State
Cycling Helpers
Explicit Setters
Hierarchical Selection

When to Use

Perfect for hierarchical selection trees, checkboxes with partial states, or any UI requiring indeterminate values.

Interactive Example

Try this:

• Click checkboxes to see tristate behavior

• Parent automatically reflects children's state

• Use buttons to set specific states

Perfect for hierarchical selection trees!

Complete Example

import { useTristate } from '@usegrand/react-hokss';

function SelectionTree() {
  const parent = useTristate('indeterminate');
  const child1 = useTristate(false);
  const child2 = useTristate(true);

  const updateParentState = () => {
    if (child1.value && child2.value) {
      parent.setTrue();
    } else if (!child1.value && !child2.value) {
      parent.setFalse();
    } else {
      parent.setIndeterminate();
    }
  };

  return (
    <div>
      <label>
        <input 
          type="checkbox" 
          checked={parent.value === true}
          ref={(el) => {
            if (el) el.indeterminate = parent.value === 'indeterminate';
          }}
          onChange={parent.cycle}
        />
        Parent ({parent.value})
      </label>
      <div style={{ marginLeft: 20 }}>
        <label>
          <input 
            type="checkbox" 
            checked={child1.value === true}
            onChange={() => {
              child1.cycle();
              updateParentState();
            }}
          />
          Child 1
        </label>
        <label>
          <input 
            type="checkbox" 
            checked={child2.value === true}
            onChange={() => {
              child2.cycle();
              updateParentState();
            }}
          />
          Child 2
        </label>
      </div>
    </div>
  );
}

API Reference

Parameters

initialValueTristateValue

Initial value (true | false | 'indeterminate')

Returns

TristateState

Object containing value and control functions

value

Current tristate value

setValue

Function to set any tristate value

setTrue

Function to set value to true

setFalse

Function to set value to false

setIndeterminate

Function to set value to indeterminate

cycle

Function to cycle through values (false → true → indeterminate → false)

reset

Function to reset to initial value