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

useShortcut

Hooks & Utilities

useShortcut React hook in TypeScript

useSelectionuseStickToBottom
Live props
Options
shortcut
enabled
preventDefault
repeat
capture
  1. Home
  2. Components
  3. Hooks & Utilities
  4. useShortcut
Free

useShortcut React hook in TypeScript

v1.0.0·Added in 1.0.0

A React keyboard shortcut hook in mod+k notation: bind shortcuts, match events and show them as ⌘K on a Mac or Ctrl+K elsewhere.

Press the shortcuts listed in the panel: the matching row lights up and the log says what ran. Type a combo into the playground (mod+k, shift+?, alt+n) to bind it live and see how it reads on Apple devices and everywhere else. Single keys like / stay quiet while you type in the search field; combos with a modifier still work there.

useShortcut 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-shortcut, together with useMediaQuery.

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

Usage

Import useShortcut from @/hooks/use-shortcut.

import { useRef } from "react"
import { useShortcut, useShortcutLabel } from "@/hooks/use-shortcut"

export function SearchField() {
  const input = useRef<HTMLInputElement>(null)
  const label = useShortcutLabel("/")

  // a bare "/" is ignored while someone types in another field
  useShortcut("/", () => input.current?.focus())
  useShortcut("mod+k", () => input.current?.focus())

  return (
    <label className="flex items-center gap-2">
      <input ref={input} placeholder="Search listings" aria-keyshortcuts={label.aria} />
      <kbd>{label.text}</kbd>
    </label>
  )
}

API

  • shortcut*default "mod+k"
    string | readonly string[] | null | undefined | false

    useShortcut(shortcut, handler, options?): the combo in mod+k notation ("shift+mod+p", "alt+n", "/", "escape"). mod is ⌘ on Apple devices and Ctrl elsewhere. Pass an array for alternatives; null, "" or false binds nothing, so a component can take a shortcut prop its caller clears.

  • handler*
    (event: KeyboardEvent) => void

    Runs when the shortcut is pressed. It may change on every render; the listener is not re-added.

  • enableddefault true
    boolean

    Turns the binding off without unmounting, for example while a panel is closed.

  • allowInInputs
    boolean

    Fire while focus is in a text field. By default only combos with ctrl, meta, mod or alt do, so a bare / or ? never steals a keystroke from someone typing.

  • preventDefaultdefault true
    boolean

    Calls event.preventDefault() when the shortcut fires, so mod+s does not also open the browser's save dialog.

  • repeatdefault false
    boolean

    Fire again while the key is held down.

  • capturedefault false
    boolean

    Listen in the capture phase, before handlers inside the page.

Parts

  • useShortcutLabel

    hook

    The display form for the current device: keys ["⇧", "⌘", "P"] for separate key caps, text "⇧⌘P" (Ctrl+Shift+P elsewhere) for menus, aria for aria-keyshortcuts. Renders the non-Apple form on the server, then swaps. Signature: (shortcut: string | null | undefined) => { keys: string[]; text: string; aria: string | undefined }.

  • formatShortcut

    function

    The same labels outside React, for a given platform. Signature: (shortcut: string, apple: boolean) => string[].

  • formatShortcutText

    function

    The same labels outside React, for a given platform. Signature: string.

  • matchesShortcut

    function

    True when a keyboard event (DOM or React) is exactly this combo. Falls back to the physical key when the layout types a non-Latin character, so mod+k also works on a Romanian or Cyrillic layout and with Option held on a Mac. Signature: (event: ShortcutEvent, shortcut: string | ParsedShortcut, apple?: boolean) => boolean.

  • parseShortcut

    function

    The parsed combo (cached), the value for aria-keyshortcuts, and whether focus sits in an input, textarea, select or contenteditable element. Signature: (shortcut: string) => ParsedShortcut | null.

  • ariaKeyShortcuts

    function

    The parsed combo (cached), the value for aria-keyshortcuts, and whether focus sits in an input, textarea, select or contenteditable element. Signature: (shortcut, apple) => string | undefined.

  • isTypingTarget

    function

    The parsed combo (cached), the value for aria-keyshortcuts, and whether focus sits in an input, textarea, select or contenteditable element. Signature: (target) => boolean.

  • UseShortcutOptions

    type

    The options object: enabled, allowInInputs, preventDefault, repeat and capture.

  • ShortcutLabel

    type

    What useShortcutLabel returns: { keys: string[]; text: string; aria: string | undefined }.

  • ParsedShortcut

    type

    What parseShortcut returns: the key plus mod, ctrl, meta, alt and shift flags.

  • ShortcutEvent

    type

    The keyboard event fields matchesShortcut reads: key, code and the modifier flags.

Examples

Keyboard list navigation

j / k or the arrows move through an inbox and Enter opens it, bound only while the list has focus.

Send with ⌘ Enter

A modified combo fires inside the textarea, so the comment sends without leaving the keyboard.

Dependencies

use-media-query

Files

  • hooks/use-shortcut.ts

FAQ

Is the useShortcut 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 useShortcut?

Run npx wingo-ui@latest add use-shortcut. It also adds the Wingo UI item it builds on (useMediaQuery). With shadcn, run npx shadcn@latest add https://wingo-ui.com/r/use-shortcut.json.

See also

KbdShortcuts DialogCommand MenuuseLongPresshookuseMediaQueryhook

Used in

Image LightboxTooltipFile managerToggleWorkflow CanvasUser MenuDropdown MenuToastModel PickerSidebarApp ShellFilter panel

and 34 more.

More React hooks and utilities

useStickToBottomhookAI ChatlibChart kitlibCommercelibDate utilslibFile exportlib
All 36 React hooks and utilities

Articles using this component

  • React Command Palette: Cmd+K, Nested Pages and Mobile

    Component guides · Oct 9, 2026 · 9 min read

PrevioususeSelectionNext useStickToBottom
  • Save listingCtrlS
  • New listingAltN
  • ShortcutsShift?
  • Your shortcutCtrlK

On a Mac⌘K·Windows and LinuxCtrl+K

{ enabled: true, preventDefault: true, repeat: false, capture: false }

Press a shortcut