Docs
useControlledState

Manage a controlled state with the useControlledState hook, providing methods to set it to true, false, or toggle between them.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-controlled-state

Usage

"use client"
 
import * as React from "react"
 
import { useControlledState } from "@/hooks/use-controlled-state"
 
export function Component() {
  const [count, setCount] = React.useState(0)
  return <CounterInput count={count} onChange={setCount} />
}
 
function CounterInput({
  count,
  onChange,
}: {
  count?: number
  onChange?: (count: number) => void
}) {
  const [value, setValue] = useControlledState<number>({
    prop: count,
    defaultProp: 0,
    onChange,
  })
 
  return (
    <div>
      <button onClick={() => setValue((prev) => (prev ?? 0) + 1)}>
        Increment
      </button>
      <p>Count: {value}</p>
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
propTThe controlled value provided by the parent component. If defined, the hook operates in controlled mode.undefinedYes
defaultPropTThe default value used in uncontrolled mode when prop is undefined.undefinedYes
onChange(state: T) => voidCallback invoked when the value changes in controlled mode or when setUncontrolledProp triggers a change.undefinedYes

Return Values

NameTypeDescription
valueT | undefinedThe current value, either from prop (controlled mode) or internal state (uncontrolled mode).
setValue(nextValue: React.SetStateAction<T | undefined>) => voidA memoized function to update the value. Accepts a new value or a function that receives the previous value and returns the new value.