Skip to content

useControllableState

Controlled or uncontrolled state with one API.

A React hook that gives a component controlled/uncontrolled behavior like native inputs. Pass value to control it, or defaultValue to leave it uncontrolled, with onChange notified in both modes.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-controllable-state

Usage

Uncontrolled by default

import { useControllableState } from "@/hooks/use-controllable-state";
 
function Counter({ value, defaultValue, onChange }) {
  const [count, setCount] = useControllableState({
    value,
    defaultValue: defaultValue ?? 0,
    onChange,
  });
 
  return <button onClick={() => setCount((c) => (c ?? 0) + 1)}>{count}</button>;
}

Controlled

function Controlled() {
  const [count, setCount] = useState(0);
 
  return <Counter value={count} onChange={setCount} />;
}

The setter accepts updater functions like useState. Updates that resolve to the same value (via Object.is) are skipped, and onChange fires only on real changes.

API

function useControllableState<T>(props: {
  value?: T;
  defaultValue?: T;
  onChange?: (value: T) => void;
}): [T | undefined, Dispatch<SetStateAction<T | undefined>>];

Parameters

Return value

A [value, setValue] tuple matching useState. setValue updates internal state only when uncontrolled, but always calls onChange.