@consentstack/react
v0.1.3
Published
React hooks and components for ConsentStack consent management
Downloads
39
Maintainers
Readme
@consentstack/react
React hooks and components for ConsentStack consent management.
Installation
npm install @consentstack/react
# or
pnpm add @consentstack/react
# or
yarn add @consentstack/reactPeer dependencies: react and react-dom ^18 or ^19.
Quick Start
Simple Usage (just the banner)
import { ConsentStack } from "@consentstack/react"
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<ConsentStack siteKey="pk_abc123" />
</body>
</html>
)
}With Hooks (conditional script loading)
import { ConsentStackProvider } from "@consentstack/react"
export default function RootLayout({ children }) {
return (
<ConsentStackProvider siteKey="pk_abc123">
{children}
</ConsentStackProvider>
)
}Hooks
useConsent()
Full consent state and control methods.
const {
consent, // Record<string, boolean> | null
config, // ConsentConfig | null
isLoading, // boolean
isReady, // boolean
error, // Error | null
setConsent, // (categories) => Promise<void>
hasConsent, // (category) => boolean
showBanner, // () => void
showPreferences, // () => void
hidePreferences, // () => void
isPreferencesOpen, // boolean
} = useConsent()useConsentValue(category)
Optimized hook for a single category. Only re-renders when that category changes.
const hasAnalytics = useConsentValue("analytics") // booleanuseConsentEvent(event, callback)
Subscribe to SDK lifecycle events. Automatically cleans up on unmount.
useConsentEvent("preferences:open", () => {
analytics.track("consent_preferences_opened")
})Events: "ready", "consent", "error", "preferences:open", "preferences:close"
Error Handling
const { error, isReady } = useConsent()
if (error) {
return <div>Consent SDK failed to load: {error.message}</div>
}The provider times out after 15 seconds by default. Customize with the timeout prop:
<ConsentStackProvider siteKey="pk_abc123" timeout={30000}>SSR Support
- Returns
isLoading: trueduring server-side rendering - Returns
falseforuseConsentValue()during SSR (safe default) - No hydration mismatches
License
MIT
