Skip to content

useControlledState

useControlledState<T>(options): [T, (next) => void]

Defined in: src/hooks/useControlledState/useControlledState.ts:42

Manage a value that may be either controlled (via prop) or uncontrolled (managed internally with a default).

Returns a [value, setValue] tuple just like useState. When options.value is defined the state is read from there and setValue becomes a pure side-effect callback that calls onChange only — internal state is never mutated. When options.value is undefined the hook owns the state and setValue updates it as well as calls onChange.

Switching between controlled and uncontrolled within a component’s lifetime is a known pitfall (matches React’s own warning for <input value/defaultValue>). The hook emits a development-only warning when this happens.

Type Parameters

T

T

Parameters

options

UseControlledStateOptions<T>

Returns

[T, (next) => void]

Example

const [value, setValue] = useControlledState({
value: props.value,
defaultValue: props.defaultValue,
onChange: props.onChange,
fallback: '',
});