Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

useControllableState

Hooks & Utilities

useControllableState React hook in TypeScript

useConsentuseCooldown
Live props
Options
defaultValue2
  1. Home
  2. Components
  3. Hooks & Utilities
  4. useControllableState
Free

useControllableState React hook in TypeScript

v1.0.0·Added in 1.0.0

A React hook for controlled and uncontrolled state: it follows a value prop when you pass one and keeps its own state when you do not.

Both steppers run on the same hook. The first keeps its own count. The second is controlled by its parent, which caps it at 5 and can reset it, so you can see who owns the value.

useControllableState is a free React hook in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add use-controllable-state.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add use-controllable-state

Usage

Import useControllableState from @/hooks/use-controllable-state.

import { useControllableState } from "@/hooks/use-controllable-state"

type ToggleProps = {
  pressed?: boolean
  defaultPressed?: boolean
  onPressedChange?: (pressed: boolean) => void
}

export function Toggle({ pressed, defaultPressed = false, onPressedChange }: ToggleProps) {
  const [on, setOn] = useControllableState({
    value: pressed,
    defaultValue: defaultPressed,
    onChange: onPressedChange,
  })

  return (
    <button type="button" aria-pressed={on} onClick={() => setOn((prev) => !prev)}>
      {on ? "On" : "Off"}
    </button>
  )
}

API

  • value
    T | undefined

    The controlled value. While it is defined the hook mirrors it and never stores its own; pass undefined to go uncontrolled.

  • defaultValue*default 2
    T

    The starting value while uncontrolled. Read once on mount, like useState.

  • onChange
    (value: T) => void

    Fires with the next value on every change, controlled or not. Skipped when the value did not change (Object.is).

  • returns
    [value: T, setValue: (next: T | ((prev: T) => T)) => void]

    The current value and a stable setter that takes a value or an updater, like useState. In controlled mode the setter only calls onChange; the parent decides.

Parts

  • UseControllableStateParams

    type

    The hook's options: { value?: T; defaultValue: T; onChange?: (value: T) => void }.

Examples

Uncontrolled toggles

Each chip owns its pressed state from defaultPressed; no parent state at all.

Same chips, controlled

The parent passes pressed and onPressedChange, so one button can flip them all.

Expand all

Disclosure sections that open on their own, driven here by a parent Expand all button.

Dependencies

No dependencies beyond React.

Files

  • hooks/use-controllable-state.ts

FAQ

Is the useControllableState hook free?

Yes. The source is free and needs no account: copy it from the Code tab or install it with the CLI.

How do I install useControllableState?

Run npx wingo-ui@latest add use-controllable-state. With shadcn, run npx shadcn@latest add https://wingo-ui.com/r/use-controllable-state.json.

See also

usePersistedStatehookuseSelectionhookQuantity stepperToggleCollapsible

Used in

CarouselAvatar UploadPowerPoint ViewerColor PickerBottom Tab BarProduct galleryCalendarSliderImage LightboxFavorite buttonTooltipLogin Page

and 198 more.

More React hooks and utilities

useCooldownhookuseDebouncehookuseKeyboardInsethookuseLocalehookuseLongPresshookuseMediaControlshook
All 36 React hooks and utilities

Articles using this component

  • React Controllable State Hook: Code and 3 Pitfalls

    Next.js and Tailwind CSS · Oct 16, 2026 · 10 min read

PrevioususeConsentNext useCooldown

Uncontrolled

defaultValue={2}
2
onChange → no changes yet

Controlled

value={quantity}
3

The parent caps it at 5

onChange → no changes yet