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

useConsent

Hooks & Utilities

useConsent React hook in TypeScript

useClipboarduseControllableState
Live props
Options
version1
storage
maxAgeDays180d
  1. Home
  2. Components
  3. Hooks & Utilities
  4. useConsent
Pro

useConsent React hook in TypeScript

v1.0.0·Added in 1.0.0

A React cookie consent hook: which categories a visitor allowed, when and under which policy version, shared by banner, links and scripts.

Press Accept all or Reject all, or flip the categories and press Save choices: the record (method, time, choices) and the Google Consent Mode values update, and the video embed loads only once Marketing is allowed. Reset forgets the decision. Raise the policy version in the playground and the stored choice no longer counts, so the site would ask again. The choice survives a reload and, with local storage, follows you to other tabs.

useConsent 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-consent, together with usePersistedState.

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

useConsent 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 useConsent from @/hooks/use-consent.

import { useConsent } from "@/hooks/use-consent"

export function YoutubeEmbed({ id }: { id: string }) {
  const { hydrated, has, save, choices } = useConsent()
  if (!hydrated) return null
  if (!has("marketing"))
    return (
      <button type="button" onClick={() => save({ ...choices, marketing: true })}>
        Allow marketing cookies to watch the video
      </button>
    )
  return <iframe title="Northwind CRM tour" src={`https://www.youtube-nocookie.com/embed/${id}`} />
}

API

  • versiondefault 1
    number

    The policy version. Bump it when the categories or the policy change: records made under another version count as undecided.

  • storagedefault "cookie"
    "cookie" | "local" | "session"

    Where the record lives. A cookie can be read on the server too (render nothing consent-dependent on the first paint when it is missing).

  • maxAgeDaysdefault 180
    number

    How long a cookie choice is kept before the visitor is asked again.

  • storageKeydefault "ui-consent"
    string

    Cookie / storage key. Every hook with the same key shares one record.

  • categories
    readonly string[]

    The category ids the site uses, default ["necessary", "preferences", "analytics", "marketing"]. necessary is always true.

  • useConsent
    (options?) => { record: ConsentRecord | null; decided; hydrated; choices; has(category); acceptAll(); rejectAll(); save(choices); reset() }

    record is { version, choices, decidedAt (ISO), method: accept-all | reject-all | custom } or null while undecided. hydrated is false on the server and during hydration: show the banner only once it is true and decided is false, so it never flashes for people who already chose.

Parts

  • getConsent

    function

    The same record outside React (a script loader, an analytics wrapper). Null on the server. Signature: (options?) => ConsentRecord | null.

  • hasConsent

    function

    The same record outside React (a script loader, an analytics wrapper). Null on the server. Signature: (category, options?) => boolean.

  • setConsent

    function

    Write a record outside React, and run code after every decision (load analytics when allowed, remove cookies when withdrawn). Signature: (record | null, options?) => void.

  • onConsentChange

    function

    Write a record outside React, and run code after every decision (load analytics when allowed, remove cookies when withdrawn). Signature: (listener: (record, key) => void) => () => void.

  • openConsentSettings

    function

    A "Cookie settings" link anywhere calls openConsentSettings(); the consent component listens with useConsentSettingsRequest and opens its settings. Signature: (storageKey?) => void.

  • useConsentSettingsRequest

    hook

    A "Cookie settings" link anywhere calls openConsentSettings(); the consent component listens with useConsentSettingsRequest and opens its settings. Signature: (handler: () => void, storageKey?) => void.

  • toGoogleConsentMode

    function

    Google Consent Mode v2 values for gtag("consent", "update", ...): analytics → analytics_storage, marketing → the three ad signals, preferences → functionality and personalization. Signature: (choices) => Record<string, "granted" | "denied">.

  • normalizeConsent

    function

    Every category present with necessary forced on; the default ids and key. Signature: (choices, categories?) => ConsentChoices.

  • DEFAULT_CONSENT_CATEGORIES

    constant

    Every category present with necessary forced on; the default ids and key. Type: readonly string[].

  • DEFAULT_CONSENT_KEY

    constant

    Every category present with necessary forced on; the default ids and key. Type: string.

Examples

Consent-gated video

has("marketing") decides between the embed and a placeholder; allowing it saves a custom record for this session only.

Dependencies

use-persisted-state

Files

  • hooks/use-consent.ts

FAQ

Is the useConsent hook free?

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

How do I install useConsent?

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

See also

usePersistedStatehookSwitchAlert

Used in

Cookie Consent

More React hooks and utilities

useControllableStatehookuseCooldownhookuseDebouncehookuseKeyboardInsethookuseLocalehookuseLongPresshook
All 36 React hooks and utilities

Articles using this component

  • Nextjs Cookie Consent: GDPR Banner and Consent Mode v2

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

PrevioususeClipboardNext useControllableState
Cookie consentReading the saved choice…
Undecided
This video uses marketing cookies.
gtag("consent", "update", {
  "ad_storage": "denied",
  "ad_user_data": "denied",
  "ad_personalization": "denied",
  "analytics_storage": "denied",
  "functionality_storage": "denied",
  "personalization_storage": "denied",
  "security_storage": "granted"
})

version: 1 · storage: cookie · maxAgeDays: 180