Use Controllable State
billui/use-controllable-stateFreeUtility
Use Controllable State component
Live preview
live · rendered by the registry
Rendered by billui on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://billui.com/r/use-controllable-state.jsonSource
1"use client";23import * as React from "react";45/**6 * Hook for components that support both controlled and uncontrolled modes.7 *8 * @param controlledValue - The controlled value (if provided)9 * @param defaultValue - The default value for uncontrolled mode10 * @param onChange - Callback fired when value changes11 * @returns A tuple of [currentValue, setValue]12 *13 * @example14 * ```tsx15 * interface Props {16 * value?: string;17 * defaultValue?: string;18 * onValueChange?: (value: string) => void;19 * }20 *21 * function Input({ value, defaultValue = "", onValueChange }: Props) {22 * const [currentValue, setValue] = useControllableState(23 * value,24 * defaultValue,25 * onValueChange,26 * );27 *28 * return (29 * <input30 * value={currentValue}31 * onChange={(e) => setValue(e.target.value)}32 * />33 * );34 * }35 * ```36 */37export function useControllableState<T>(38 controlledValue: T | undefined,39 defaultValue: T,40 onChange?: (value: T) => void,41): [T, (value: T) => void] {42 const [internalValue, setInternalValue] = React.useState(defaultValue);43 const isControlled = controlledValue !== undefined;44 const value = isControlled ? controlledValue : internalValue;4546 const setValue = React.useCallback(47 (newValue: T) => {48 if (!isControlled) {49 setInternalValue(newValue);50 }51 onChange?.(newValue);52 },53 [isControlled, onChange],54 );5556 return [value, setValue];57}
Files it writes
More from billui
All 13 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Billing Address Databilling-address-data | billui | Utilities | Free | no deps | |
| Utilsutils | billui | Utilities | Free | 2 deps |
