OpenPolicy

Hooks

React hooks for reading and managing cookie consent state

See the Quick Start to get set up first.

useCookies

The primary hook for working with consent state. Powers CookieBanner, CookiePreferences, and ConsentGate internally — use it directly when building custom UIs or gating content in application code.

import { useCookies } from "@openpolicy/react";

const { route, categories, acceptAll, acceptNecessary, setRoute, has } = useCookies();

Must be called inside an <OpenPolicy> provider.

Return value

PropertyTypeDescription
route"cookie" | "preferences" | "closed"Which UI screen to show
categories{ key, label, enabled, locked }[]Consent categories from config
acceptAll() => voidEnable all categories and close
acceptNecessary() => voidEnable only essential categories and close
toggle(key: string) => voidToggle a category in the preferences panel
save() => voidPersist current toggle state and close
reject() => voidDisable all non-essential categories and close
setRoute(screen: "cookie" | "preferences" | "closed") => voidProgrammatically set which UI screen to show
has(expr: string | ConsentExpr) => booleanCheck consent for a category or expression

Decisions are stored in localStorage under op_consent as a map of category keys to booleans:

{ "essential": true, "analytics": true, "marketing": false }

ConsentGate

A component that renders its children only when the required consent is granted.

import { ConsentGate } from "@openpolicy/react";

<ConsentGate requires="analytics">
  <GoogleAnalytics />
</ConsentGate>

<ConsentGate requires={{ and: ["analytics", "marketing"] }} fallback={<p>Consent required.</p>}>
  <RetargetingPixel />
</ConsentGate>
PropTypeDefaultDescription
requiresstring | ConsentExprCategory key or { and } / { or } expression
fallbackReactNodenullRendered when consent is not granted

On this page