@consentify/react
React hook for reactive consent state management.
@consentify/react provides a thin React hook that subscribes to consent state from @consentify/core via useSyncExternalStore. SSR-safe, concurrent-mode friendly.
Installation
npm install @consentify/react @consentify/coreuseConsentify(instance)
Returns the full consent state and re-renders on changes.
'use client';
import { useConsentify } from '@consentify/react';
import { consentify } from '@/lib/consentify';
export function ConsentBanner() {
const state = useConsentify(consentify);
if (state.decision === 'decided') return null;
return (
<div role="dialog" aria-label="Cookie consent">
<h2>Cookie Preferences</h2>
<p>We use cookies to improve your experience.</p>
<button onClick={() => consentify.acceptAll()}>Accept All</button>
<button onClick={() => consentify.rejectAll()}>Reject All</button>
</div>
);
}useConsentify(instance, category) — category overload
When you only need a boolean for one category, pass it as the second argument:
function AnalyticsLoader() {
const analyticsGranted = useConsentify(consentify, 'analytics');
return analyticsGranted ? <GoogleAnalytics /> : null;
}This avoids re-renders from unrelated category changes and keeps the component tree clean.
Reading Choices
function ScriptLoaders() {
const state = useConsentify(consentify);
if (state.decision !== 'decided') return null;
const { choices } = state.snapshot;
return (
<>
{choices.analytics && <GoogleAnalytics />}
{choices.marketing && <FacebookPixel />}
</>
);
}How It Works
The hook subscribes via useSyncExternalStore(instance.subscribe, instance.get, instance.getServerSnapshot). It:
- Renders
{ decision: 'unset' }on the server (SSR-safe default) - Hydrates from the actual cookie on the client
- Re-renders on
set(),clear(), or multi-tab sync
Re-exports
@consentify/react re-exports everything from @consentify/core, so you can import both from the same entry:
import { useConsentify, createConsentify, enableConsentMode } from '@consentify/react';Server Components
useConsentify is a client-side hook. To read consent in a Server Component, use the server API from @consentify/core:
import { cookies } from 'next/headers';
import { consentify } from '@/lib/consentify';
export default async function Page() {
const state = consentify.get((await cookies()).toString());
// render conditionally based on `state`
}