Playground

useControllableState

The value, defaultValue and onChange pattern for custom components that can be controlled or uncontrolled.

  • No DOM output. Lets a custom widget accept value/defaultValue/onValueChange like the Monoline components do.
  • onChange fires only when the new value differs from the current one.

Import

import '@monoline/css';
import {useControllableState} from '@monoline/react';

Not installed yet? Pick a route.

Copies the source and its styles into your project.

npx monoline add use-controllable-state

Usage

import {Button, useControllableState} from '@monoline/react';

interface CounterProps {
  value?: number;
  defaultValue?: number;
  onValueChange?: (value: number) => void;
}

function Counter({value, defaultValue = 0, onValueChange}: CounterProps) {
  const [count, setCount] = useControllableState({value, defaultValue, onChange: onValueChange});
  return (
    <div>
      <Button variant="line" aria-label="Decrease" onClick={() => setCount(count - 1)}>−</Button>{' '}
      <output>{count}</output>{' '}
      <Button variant="line" aria-label="Increase" onClick={() => setCount(count + 1)}>+</Button>
    </div>
  );
}

<Counter defaultValue={2} />

Examples

Uncontrolled

Starts at defaultValue and keeps its own state.

Controlled

The parent owns the value and rounds it to the nearest 5 before storing it.

Props

UseControllableStateOptions

PropTypeDefaultDescription
valueT–When defined, the hook is controlled and `value` wins.
defaultValue requiredT–Starting value when uncontrolled.
onChange((value: T) => void)–Called with the new value when it differs from the current one.

Behaviour

  • No DOM output. Lets a custom widget accept value/defaultValue/onValueChange like the Monoline components do.
  • onChange fires only when the new value differs from the current one.