Controllable State Hook
ncdai/use-controllable-stateUnverifiedHook
ncdai publishes no description for this item.
Install it
npx shadcn@latest add https://raw.githubusercontent.com/Prathamesh-exe/prathfolio/main/chanhdai.com/public/r/use-controllable-state.jsonSource
1// Thanks @radix-ui23import * as React from "react"45// use-layout-effect.tsx6// https://github.com/radix-ui/primitives/blob/main/packages/react/use-layout-effect/src/use-layout-effect.tsx78/**9 * On the server, React emits a warning when calling `useLayoutEffect`.10 * This is because neither `useLayoutEffect` nor `useEffect` run on the server.11 * We use this safe version which suppresses the warning by replacing it with a noop on the server.12 *13 * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect14 */15const useLayoutEffect = globalThis?.document ? React.useLayoutEffect : () => {}1617// use-controllable-state.tsx18// https://github.com/radix-ui/primitives/blob/main/packages/react/use-controllable-state/src/use-controllable-state.tsx1920// Prevent bundlers from trying to optimize the import21const useInsertionEffect: typeof useLayoutEffect =22 (React as never)[" useInsertionEffect ".trim().toString()] || useLayoutEffect2324type ChangeHandler<T> = (state: T) => void25type SetStateFn<T> = React.Dispatch<React.SetStateAction<T>>2627interface UseControllableStateParams<T> {28 prop?: T | undefined29 defaultProp: T30 onChange?: ChangeHandler<T>31 caller?: string32}3334export function useControllableState<T>({35 prop,36 defaultProp,37 onChange = () => {},38 caller,39}: UseControllableStateParams<T>): [T, SetStateFn<T>] {40 const [uncontrolledProp, setUncontrolledProp, onChangeRef] =41 useUncontrolledState({42 defaultProp,43 onChange,44 })45 const isControlled = prop !== undefined46 const value = isControlled ? prop : uncontrolledProp4748 // OK to disable conditionally calling hooks here because they will always run49 // consistently in the same environment. Bundlers should be able to remove the50 // code block entirely in production.51 /* eslint-disable react-hooks/rules-of-hooks */52 if (process.env.NODE_ENV !== "production") {53 const isControlledRef = React.useRef(prop !== undefined)54 React.useEffect(() => {55 const wasControlled = isControlledRef.current56 if (wasControlled !== isControlled) {57 const from = wasControlled ? "controlled" : "uncontrolled"58 const to = isControlled ? "controlled" : "uncontrolled"59 console.warn(60 `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`61 )62 }63 isControlledRef.current = isControlled64// … truncated
Files it writes
More from ncdai
All 17 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Sound Hookuse-sound | ncdai | Hooks | Unverified | no deps |
