Hooks
The cookies-consent package provides hooks for accessing and managing consent state.
useConsent
The main hook for accessing consent state and actions.
Returns
| Property | Type | Description |
|---|---|---|
consent | ConsentState | Full consent state object |
hasConsented | boolean | Whether user has made a choice |
isOpen | boolean | Whether consent banner is open |
openPreferences | () => void | Open the consent banner |
closePreferences | () => void | Close the consent banner |
acceptAll | () => void | Accept all cookies |
acceptEssentialOnly | () => void | Accept only essential cookies |
isAllowed | (category: CookieCategory) => boolean | Check 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;
}
Example: Cookie Settings Button
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
| Property | Type | Description |
|---|---|---|
hasConsented | boolean | Whether user has made a choice |
functionalAllowed | boolean | Functional cookies enabled |
statisticsAllowed | boolean | Statistics cookies enabled |
marketingAllowed | boolean | Marketing cookies enabled |
withConsent | (category, fn) => void | Execute 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
| Property | Type | Description |
|---|---|---|
hasConsented | boolean | Whether user has made a choice |
categories | Record<CookieCategory, CategoryStatus> | Status per category |
isAllowed | (category: CookieCategory) => boolean | Check if category is allowed |
hasActiveCookies | (category: CookieCategory) => boolean | Check if cookies detected |
getActiveCookies | (category: CookieCategory) => string[] | Get detected cookie names |
isCookiePresent | (cookieName: string) => boolean | Check if specific cookie exists |
totalCookies | number | Total detected cookies across all categories |
refresh | () => void | Manually 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
| Property | Type | Description |
|---|---|---|
cookies | DetectedCookie[] | All detected cookies |
byCategory | Record<Category, DetectedCookie[]> | Cookies grouped by category |
byService | Record<string, DetectedCookie[]> | Cookies grouped by service |
summary | object | Summary statistics |
isLoading | boolean | Whether initial detection is loading |
refresh | () => void | Manually 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
| Property | Type | Description |
|---|---|---|
items | DetectedStorageItem[] | All detected storage items |
byCategory | Record<Category, DetectedStorageItem[]> | Items grouped by category |
byType | Record<StorageType, DetectedStorageItem[]> | Items grouped by storage type |
byService | Record<string, DetectedStorageItem[]> | Items grouped by service |
summary | object | Summary statistics |
isLoading | boolean | Whether initial detection is loading |
refresh | () => void | Manually 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
| Property | Type | Description |
|---|---|---|
data | DetectedBrowserData[] | All detected browser data |
byCategory | Record<Category, DetectedBrowserData[]> | Data grouped by category |
byDataType | Record<DataType, DetectedBrowserData[]> | Data grouped by type |
byService | Record<string, DetectedBrowserData[]> | Data grouped by service |
summary | object | Summary statistics |
isLoading | boolean | Whether initial detection is loading |
refresh | () => void | Manually 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>
);
}
Cookie Categories
The following categories can be checked with isAllowed():
| Category | Key | Description |
|---|---|---|
| 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