useControllableState
One state value that works controlled or uncontrolled, with the value / defaultValue / onChange shape every UnflowUI component uses.
Overview
useControllableState lets a component accept value + onChange (controlled) or only defaultValue (uncontrolled) without writing both code paths. While value is undefined the hook keeps its own state; once a value is passed it uses that instead. onChange is called in both modes.
It backs the value/defaultValue/onValueChange props of Accordion, Tabs, Sidebar, SidePanel, Search, CommandPalette, QuickFilter, the Authentication block and the DataTable models (sort, filter, pagination, selection, columns).
Import
import { useControllableState } from '@unflowio/ui/hooks/useControllableState';Parameters
const [value, setValue] = useControllableState(value, onChange, defaultValue);| Param | Type | Description |
|---|---|---|
value | T | undefined | The controlled value. undefined means uncontrolled |
onChange | ((next: T) => void) | undefined | Called with every new value, in both modes |
defaultValue | T | Required. The starting value while uncontrolled |
Return value
A tuple, like useState:
| Index | Type | Description |
|---|---|---|
[0] | T | The current value: value when controlled, the internal state otherwise |
[1] | (next: T) => void | Sets the value. Updates the internal state when uncontrolled, then calls onChange |
Usage
import { useControllableState } from '@unflowio/ui/hooks/useControllableState';
interface ToggleGroupProps {
options: string[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
}
function ToggleGroup({ options, value, defaultValue, onValueChange }: ToggleGroupProps) {
const [selected, setSelected] = useControllableState(
value,
onValueChange,
defaultValue ?? options[0] ?? '',
);
return (
<div role="group">
{options.map((option) => (
<button
key={option}
aria-pressed={selected === option}
onClick={() => setSelected(option)}
>
{option}
</button>
))}
</div>
);
}Both of these work:
<ToggleGroup options={['Day', 'Week']} defaultValue="Week" />
<ToggleGroup options={['Day', 'Week']} value={range} onValueChange={setRange} />Implementation notes
undefined means uncontrolled. Use null (or another sentinel) when "no value" must stay controlled. Switching between undefined and a value at runtime switches mode, as with React's own inputs; avoid it.
defaultValue is read once. Like useState's initial value, changing it after mount has no effect.
Setter takes a value, not an updater. setValue(next) doesn't accept (prev) => next. Compute the next value from the returned value.