Skip to main content

Hooks

The cookies-consent package provides hooks for accessing and managing consent state.

useConsent

The main hook for accessing consent state and actions.

Returns

PropertyTypeDescription
consentConsentStateFull consent state object
hasConsentedbooleanWhether user has made a choice
isOpenbooleanWhether consent banner is open
openPreferences() => voidOpen the consent banner
closePreferences() => voidClose the consent banner
acceptAll() => voidAccept all cookies
acceptEssentialOnly() => voidAccept only essential cookies
isAllowed(category: CookieCategory) => booleanCheck if category is allowed

Usage

import { useConsent } from "@elcto/cookies-consent";

function AnalyticsLoader() {
const { hasConsented, isAllowed } = useConsent();

useEffect(() => {
if (hasConsented && isAllowed("statistics")) {
// Initialize Google Analytics
loadGoogleAnalytics();
}
}, [hasConsented, isAllowed]);

return null;
}
import { useConsent } from "@elcto/cookies-consent";
import { Cookie } from "lucide-react";

function CookieSettingsMenuItem() {
const { openPreferences } = useConsent();

return (
<button onClick={openPreferences}>
<Cookie className="w-4 h-4" />
Cookie Settings
</button>
);
}

Example: Conditional Content

import { useConsent } from "@elcto/cookies-consent";

function YouTubeEmbed({ videoId }: { videoId: string }) {
const { isAllowed, openPreferences } = useConsent();

if (!isAllowed("functional")) {
return (
<div className="placeholder">
<p>YouTube videos require functional cookies.</p>
<button onClick={openPreferences}>
Enable Cookies
</button>
</div>
);
}

return (
<iframe
src={`https://www.youtube.com/embed/${videoId}`}
allowFullScreen
/>
);
}

useCookiePreferences

A convenience hook for common consent checks.

Returns

PropertyTypeDescription
hasConsentedbooleanWhether user has made a choice
functionalAllowedbooleanFunctional cookies enabled
statisticsAllowedbooleanStatistics cookies enabled
marketingAllowedbooleanMarketing cookies enabled
withConsent(category, fn) => voidExecute function if category allowed

Usage

import { useCookiePreferences } from "@elcto/cookies-consent";

function ThirdPartyIntegrations() {
const {
functionalAllowed,
statisticsAllowed,
withConsent
} = useCookiePreferences();

useEffect(() => {
withConsent("statistics", () => {
initAnalytics();
});

withConsent("functional", () => {
initChatWidget();
});
}, [withConsent]);

return (
<div>
{functionalAllowed && <ChatWidget />}
{statisticsAllowed && <AnalyticsDashboard />}
</div>
);
}

useCookieStatus

Combines consent status with cookie detection to provide real-time cookie status.

Returns

PropertyTypeDescription
hasConsentedbooleanWhether user has made a choice
categoriesRecord<CookieCategory, CategoryStatus>Status per category
isAllowed(category: CookieCategory) => booleanCheck if category is allowed
hasActiveCookies(category: CookieCategory) => booleanCheck if cookies detected
getActiveCookies(category: CookieCategory) => string[]Get detected cookie names
isCookiePresent(cookieName: string) => booleanCheck if specific cookie exists
totalCookiesnumberTotal detected cookies across all categories
refresh() => voidManually refresh cookie detection

CategoryStatus Type

interface CategoryStatus {
allowed: boolean; // User consented to this category
hasActiveCookies: boolean; // Cookies detected in this category
activeCookieCount: number; // Number of detected cookies
cookies: string[]; // Names of detected cookies
}

Usage

import { useCookieStatus } from "@elcto/cookies-consent";

function CookieMonitor() {
const {
categories,
hasActiveCookies,
getActiveCookies,
totalCookies,
refresh
} = useCookieStatus();

return (
<div>
<p>Total active cookies: {totalCookies}</p>

{Object.entries(categories).map(([cat, status]) => (
<div key={cat}>
<span>{cat}: </span>
{status.allowed ? "Allowed" : "Blocked"}
{status.hasActiveCookies && ` (${status.activeCookieCount} active)`}
</div>
))}

<button onClick={refresh}>Refresh</button>
</div>
);
}

Example: Analytics Status

import { useCookieStatus } from "@elcto/cookies-consent";

function AnalyticsStatus() {
const { categories, hasActiveCookies } = useCookieStatus();
const stats = categories.statistics;

if (!stats.allowed) {
return <span>Analytics disabled</span>;
}

if (!hasActiveCookies("statistics")) {
return <span>Analytics allowed, no cookies yet</span>;
}

return (
<span>
Analytics active ({stats.activeCookieCount} cookies)
</span>
);
}

useConsentContext

Low-level hook that provides the raw context value. Use useConsent instead for most cases.

import { useConsentContext } from "@elcto/cookies-consent";

// Must be used within ConsentProvider
const context = useConsentContext();

useCookieDetector

Detects and monitors cookies in the browser.

Returns

PropertyTypeDescription
cookiesDetectedCookie[]All detected cookies
byCategoryRecord<Category, DetectedCookie[]>Cookies grouped by category
byServiceRecord<string, DetectedCookie[]>Cookies grouped by service
summaryobjectSummary statistics
isLoadingbooleanWhether initial detection is loading
refresh() => voidManually refresh detection

Usage

import { useCookieDetector } from "@elcto/cookies-consent";

function CookieList() {
const { cookies, byCategory, summary, refresh } = useCookieDetector();

return (
<div>
<p>Total cookies: {summary.total}</p>
<p>Essential: {summary.byCategory.essential}</p>
<button onClick={refresh}>Refresh</button>
</div>
);
}

useStorageDetector

Detects and monitors browser storage (localStorage and sessionStorage).

Returns

PropertyTypeDescription
itemsDetectedStorageItem[]All detected storage items
byCategoryRecord<Category, DetectedStorageItem[]>Items grouped by category
byTypeRecord<StorageType, DetectedStorageItem[]>Items grouped by storage type
byServiceRecord<string, DetectedStorageItem[]>Items grouped by service
summaryobjectSummary statistics
isLoadingbooleanWhether initial detection is loading
refresh() => voidManually refresh detection

Usage

import { useStorageDetector } from "@elcto/cookies-consent";

function StorageList() {
const { items, byType, summary, refresh } = useStorageDetector();

return (
<div>
<p>Total storage items: {summary.total}</p>
<p>localStorage: {summary.byType.localStorage}</p>
<p>sessionStorage: {summary.byType.sessionStorage}</p>

<h3>localStorage Items</h3>
{byType.localStorage.map(item => (
<div key={item.key}>
{item.key}: {item.service || "Unknown"}
</div>
))}
</div>
);
}

useBrowserDataDetector

Combined hook that detects both cookies and browser storage.

Returns

PropertyTypeDescription
dataDetectedBrowserData[]All detected browser data
byCategoryRecord<Category, DetectedBrowserData[]>Data grouped by category
byDataTypeRecord<DataType, DetectedBrowserData[]>Data grouped by type
byServiceRecord<string, DetectedBrowserData[]>Data grouped by service
summaryobjectSummary statistics
isLoadingbooleanWhether initial detection is loading
refresh() => voidManually refresh detection

Usage

import { useBrowserDataDetector } from "@elcto/cookies-consent";

function BrowserDataOverview() {
const { data, byDataType, summary } = useBrowserDataDetector();

return (
<div>
<h2>Browser Data Overview</h2>
<p>Total items: {summary.total}</p>
<ul>
<li>Cookies: {summary.byDataType.cookie}</li>
<li>localStorage: {summary.byDataType.localStorage}</li>
<li>sessionStorage: {summary.byDataType.sessionStorage}</li>
</ul>

<h3>By Category</h3>
<ul>
<li>Essential: {summary.byCategory.essential}</li>
<li>Functional: {summary.byCategory.functional}</li>
<li>Statistics: {summary.byCategory.statistics}</li>
<li>Marketing: {summary.byCategory.marketing}</li>
</ul>
</div>
);
}

The following categories can be checked with isAllowed():

CategoryKeyDescription
Essential"essential"Always true, cannot be disabled
Functional"functional"Third-party integrations, preferences
Statistics"statistics"Analytics and usage tracking
Marketing"marketing"Advertising and retargeting
const { isAllowed } = useConsent();

isAllowed("essential"); // Always true
isAllowed("functional"); // Based on user choice
isAllowed("statistics"); // Based on user choice
isAllowed("marketing"); // Based on user choice