useUncontrolled
Manages a value as either controlled or uncontrolled, the same dual-mode pattern this kit's own form components use.
useUncontrolled manages the state of a value that can be either controlled or uncontrolled — the same pattern the kit's own form components (Switch, Checkbox, Combobox, ...) use under the hood. Reach for it when building a custom component that should support both value/onChange (controlled) and defaultValue (uncontrolled) the way a native <input> does.
import { useUncontrolled } from '@42/ui-react';
function Toggle({ value, defaultValue, onChange }) {
const [checked, setChecked] = useUncontrolled({
value,
defaultValue,
finalValue: false,
onChange,
});
return <button onClick={() => setChecked((c) => !c)}>{checked ? 'On' : 'Off'}</button>;
}The state is controlled whenever value is provided — defaultValue is ignored in that case — and uncontrolled otherwise. null is a valid value; use it instead of undefined when a controlled value is optional, since undefined is what makes the component fall back to uncontrolled mode.
Usage
The same custom toggle component, shown once uncontrolled (manages its own state) and once controlled (state lives in the parent).
Code
function Toggle({ value, defaultValue, onChange }) { const [checked, setChecked] = useUncontrolled({ value, defaultValue, finalValue: false, onChange }); return <button onClick={() => setChecked((c) => !c)}>{checked ? 'On' : 'Off'}</button>;}// Uncontrolled<Toggle defaultValue={false} />// Controlledconst [value, setValue] = useState(false);<Toggle value={value} onChange={setValue} />API
Parameters
Prop
Type
Returns
A [value, setValue, isControlled] tuple.
Prop
Type