use-controllable-value
shadcn-hooks/use-controllable-valueFreeHook
A hook to manage a controllable value
Install it
npx shadcn@latest add https://shadcn-hooks.com/r/use-controllable-value.jsonSource
1import { isFunction } from 'es-toolkit/predicate'2import { useMemo, useRef } from 'react'3import { useMemoizedFn } from '@/registry/hooks/use-memoized-fn'4import { useUpdate } from '@/registry/hooks/use-update'5import type { SetStateAction } from 'react'67export interface Options<T> {8 defaultValue?: T9 defaultValuePropName?: string10 valuePropName?: string11 trigger?: string12}1314export type Props = Record<string, any>1516export interface StandardProps<T> {17 value: T18 defaultValue?: T19 onChange: (val: T) => void20}2122function useControllableValue<T = any>(23 props: StandardProps<T>,24): [T, (v: SetStateAction<T>) => void]25function useControllableValue<T = any>(26 props?: Props,27 options?: Options<T>,28): [T, (v: SetStateAction<T>, ...args: any[]) => void]29function useControllableValue<T = any>(30 defaultProps?: Props,31 options: Options<T> = {},32) {33 const props = defaultProps ?? {}3435 const {36 defaultValue,37 defaultValuePropName = 'defaultValue',38 valuePropName = 'value',39 trigger = 'onChange',40 } = options4142 const value = props[valuePropName] as T43 const isControlled = Object.prototype.hasOwnProperty.call(44 props,45 valuePropName,46 )4748 const initialValue = useMemo(() => {49 if (isControlled) {50 return value51 }52 if (Object.prototype.hasOwnProperty.call(props, defaultValuePropName)) {53 return props[defaultValuePropName]54 }55 return defaultValue56 }, [])5758 const stateRef = useRef(initialValue)59 if (isControlled) {60 stateRef.current = value61 }6263 const update = useUpdate()6465 const setState = (v: SetStateAction<T>, ...args: any[]) => {66 const r = isFunction(v) ? v(stateRef.current) : v6768 if (!isControlled) {69 stateRef.current = r70 update()71 }72 if (props[trigger]) {73 props[trigger](r, ...args)74 }75 }7677 return [stateRef.current, useMemoizedFn(setState)] as const78}7980export { useControllableValue }
What it pulls in
npm packages
Other registry items
Files it writes
More from shadcn-hooks
All 58 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| use-active-elementuse-active-element | shadcn-hooks | Hooks | Free | no deps | |
| use-batteryuse-battery | shadcn-hooks | Hooks | Free | no deps | |
| use-booleanuse-boolean | shadcn-hooks | Hooks | Free | no deps | |
| use-click-any-whereuse-click-any-where | shadcn-hooks | Hooks | Free | no deps | |
| use-click-awayuse-click-away | shadcn-hooks | Hooks | Free | no deps | |
| use-clipboarduse-clipboard | shadcn-hooks | Hooks | Free | no deps | |
| use-counteruse-counter | shadcn-hooks | Hooks | Free | no deps | |
| use-creationuse-creation | shadcn-hooks | Hooks | Free | 1 dep |
