Skip to main content

createControllableValue

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

View as Markdown

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#

import { createControllableValue } from 'moraine/utils'

Signature#

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#

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.