useControlled

A React hook to manage controlled versus uncontrolled state for a component.

This hook encapsulates the logic required to allow a component to work either in a controlled mode (where the parent component manages the state) or in an uncontrolled mode (where the component itself manages the state).

  • @param options - The hook options.
  • @param options.controlled - The controlled value; if defined, the component is controlled.
  • @param options.default - The initial default value when uncontrolled (used only on first render).
  • @param options.name - The component name for warning messages.
  • @param options.state - (Optional) The state variable name (defaults to “value”) for warnings.
  • @returns A tuple with the current value and a setter. In controlled mode, the setter is a no-op.

Example

function ExampleComponent(props) {
  const { value: valueProp, defaultValue, children } = props
 
  const [value, setValue] = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'ExampleComponent',
  })
 
  // ...
}