---
title: createControllableValue
description: Bridge controlled and uncontrolled component state with a single
  reactive accessor and setter pair.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# createControllableValue

> Bridge controlled and uncontrolled component state with a single reactive accessor and setter pair.

`createControllableValue` bridges controlled and uncontrolled state for a custom component. It follows the caller's value while `value()` is defined, and otherwise keeps its own state, seeded from `defaultValue()`.

## Import

```tsx
import { createControllableValue } from 'moraine/utils'
```

## Signature

```ts
function createControllableValue<T>(
  options: CreateControllableValueOptions<T>,
): readonly [Accessor<T>, (update: T | ((previous: T) => T)) => void]

interface CreateControllableValueOptions<T> {
  value: Accessor<T | undefined>
  defaultValue: Accessor<T>
  onChange?: (value: T) => void
}
```

## Usage Example

```tsx title="src/CustomToggle.tsx"
import { createControllableValue } from 'moraine/utils'

interface CustomToggleProps {
  checked?: boolean
  defaultChecked?: boolean
  onCheckedChange?: (checked: boolean) => void
}

export function CustomToggle(props: CustomToggleProps) {
  const [checked, setChecked] = createControllableValue({
    value: () => props.checked,
    defaultValue: () => props.defaultChecked ?? false,
    onChange: (next) => props.onCheckedChange?.(next),
  })

  return (
    <button
      type="button"
      aria-pressed={checked()}
      onClick={() => setChecked((previous) => !previous)}
      class="px-3 py-1.5 rounded-md border"
    >
      {checked() ? 'Active' : 'Inactive'}
    </button>
  )
}
```

## Behavior

- **Controlled**: When `value()` returns a defined value, the accessor returns it. The setter does not change internal state. It calls `onChange` with the next value, and the caller updates `value`.
- **Uncontrolled**: When `value()` returns `undefined`, the hook holds the state internally, seeded from `defaultValue()`. The setter updates that state and calls `onChange`.
- `defaultValue()` is read once, when the hook runs.
- The setter accepts a value or an updater function that receives the current value.
- The setter skips `onChange` when the next value is `Object.is`-equal to the current one.

