Lynx
useControllableState
A hook that supports controlled/uncontrolled state patterns.
Available since@seed-design/lynx-react-use-controllable-state@0.1.0
Installation
Import
useControllableState is a standalone package that can be used without styles. You can use it without installing @seed-design/lynx-react.
The existing useControllableState re-export from @seed-design/lynx-react is also maintained. For new code, it is recommended to import directly from the standalone package above.
Usage
Uncontrolled (Default)
defaultValue only determines the initial state. To control the value externally after that, pass value.
Controlled
In controlled mode, the setter calls onChange, and the actual value only changes when the parent updates value. value={undefined} means uncontrolled mode, so keep the mode consistent while in use.
API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
value | T | undefined | - | The controlled value. When provided, operates in controlled mode. |
defaultValue | T | (required) | The initial value in uncontrolled mode. |
onChange | (value: T) => void | - | Called when the setter is passed a value different from the current one. Not called by the initial render or by an external value change alone. |
Return
Returns a [T, (value: T) => void] tuple.
- First element: the current value
- Second element: the setter function that changes the value (stable reference). It takes the next value directly and does not support a functional updater.
Differences from the Web Version
| Item | Lynx (useControllableState) | Web (react-headless) |
|---|---|---|
| Dev warning | None | Warns on controlled ↔ uncontrolled transition |
| onChange signature | (value: T) => void | (value: T, ...details: any[]) => void |
| Setter signature | (value: T) => void | (value: T | ((prev: T) => T)) => void |
| Dependency | @lynx-js/lynx-ui-common | Own implementation |