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

useSelection

Hooks & Utilities

useSelection React hook in TypeScript

useScrollStateuseShortcut
Live props
Options
mode
allowDeselect
  1. Home
  2. Components
  3. Hooks & Utilities
  4. useSelection
Pro

useSelection React hook in TypeScript

v1.0.0·Added in 1.0.0

A React selection hook for lists, tables and grids: single or multiple, Shift-click ranges, and select all with an indeterminate state.

Tick customers in the list; hold Shift and tick another to select everything between them. The header checkbox shows the indeterminate state and selects or clears all (the archived customer stays unselectable). Switch to single mode to pick one at a time; clicking it again clears it.

useSelection is a Pro 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-selection, together with useControllableState.

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-selection

useSelection is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import useSelection from @/hooks/use-selection.

import { useSelection } from "@/hooks/use-selection"

const clients = [
  { id: "c1", name: "Northwind Tech LLC" },
  { id: "c2", name: "Summit Logistics Inc." },
  { id: "c3", name: "Greenleaf Pharmacy" },
]

export function ClientPicker() {
  const selection = useSelection({ keys: clients.map((c) => c.id) })
  return (
    <ul>
      {clients.map((client) => (
        <li key={client.id}>
          <label>
            <input
              type="checkbox"
              checked={selection.isSelected(client.id)}
              onClick={(event) => selection.handleSelect(client.id, event)}
              readOnly
            />
            {client.name}
          </label>
        </li>
      ))}
    </ul>
  )
}

API

  • modedefault "multiple"
    "single" | "multiple"

    single keeps at most one key (radio-like rows); multiple is for bulk actions.

  • allowDeselectdefault true
    boolean

    Single mode: selecting the selected key again clears the selection.

  • keys*
    readonly string[]

    Every selectable key in display order. Shift ranges walk this order; select all takes all of them.

  • value / defaultValue / onValueChange
    string[]

    Controlled or uncontrolled through useControllableState. onValueChange gets the keys in display order.

  • disabledKeys
    readonly string[]

    Keys that cannot be selected: toggle ignores them, ranges and select all skip them.

  • useSelection (result)
    { selected; isSelected(key); isDisabled(key); toggle(key, { range?, additive? }); handleSelect(key, event); select; deselect; selectRange(from, to); selectAll; clear; setSelected(keys); toggleAll; allSelected; someSelected; checkedState: boolean | "indeterminate"; count }

    handleSelect reads shiftKey from the click or key event (pass it straight from onClick / onCheckedChange's event). checkedState feeds a header Checkbox. Rendering stays yours: aria-selected / aria-checked and data-selected on the rows.

Parts

  • SelectionMode

    type

    "single" | "multiple".

  • UseSelectionOptions

    type

    The options object: keys, mode, value, defaultValue, onValueChange, disabledKeys and allowDeselect.

  • SelectionModifiers

    type

    The second argument of toggle: { range?: boolean; additive?: boolean }.

  • UseSelectionResult

    type

    The return value: selected keys, checks, actions, allSelected, someSelected, checkedState, count and handleSelect.

Examples

Bulk actions

Select invoices (Shift-click for a range) and the header turns into an action bar with the total.

Single choice cards

mode="single" with allowDeselect off: plan cards that always keep one selected.

Dependencies

use-controllable-state

Files

  • hooks/use-selection.ts

FAQ

Is the useSelection hook free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install useSelection?

Run npx wingo-ui@latest add use-selection. It also adds the Wingo UI item it builds on (useControllableState). With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/use-selection.

See also

CheckboxData TableListboxToolbaruseControllableStatehook

Used in

File managerData TableFile ListTagTree ViewList

More React hooks and utilities

useShortcuthookuseStickToBottomhookAI ChatlibChart kitlibCommercelibDate utilslib
All 36 React hooks and utilities
PrevioususeScrollStateNext useShortcut
Customers0 selected
  • Northwind Tech LLCNew York
  • Summit Logistics Inc.Chicago
  • Olivia Hayes ConsultingAustin
  • Greenleaf PharmacyBoston
  • Ironclad BuildersDenver · archived
  • Old Mill BakeryPortland

multiple · []