useControlledState
sora-ui/hooks-use-controlled-stateFreeHook
A hook that allows you to control a state.
Install it
npx shadcn@latest add https://ui.soralabs.io.vn/r/hooks-use-controlled-state.jsonSource
1import * as React from "react";23interface CommonControlledStateProps<T> {4 defaultValue?: T;5 value?: T;6}78// eslint-disable-next-line @typescript-eslint/no-explicit-any9export function useControlledState<T, Rest extends any[] = []>(10 props: CommonControlledStateProps<T> & {11 onChange?: (value: T, ...args: Rest) => void;12 }13): readonly [T, (next: T, ...args: Rest) => void] {14 const { value, defaultValue, onChange } = props;1516 const [state, setInternalState] = React.useState<T>(17 value === undefined ? (defaultValue as T) : value18 );1920 React.useEffect(() => {21 if (value !== undefined) {22 setInternalState(value);23 }24 }, [value]);2526 const setState = React.useCallback(27 (next: T, ...args: Rest) => {28 setInternalState(next);29 onChange?.(next, ...args);30 },31 [onChange]32 );3334 return [state, setState] as const;35}
Files it writes
More from Sora UI
All 97 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAutoHeighthooks-use-auto-height | Sora UI | Hooks | Free | no deps | |
| useIsInViewhooks-use-is-in-view | Sora UI | Hooks | Free | 1 dep | |
| usePrefersReducedMotionhooks-use-prefers-reduced-motion | Sora UI | Hooks | Free | no deps |
