nextjs-cookie-consent
Version:
A GDPR/DSGVO-compliant cookie consent banner for Next.js
24 lines (23 loc) • 984 B
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useState, useCallback } from 'react';
// Context
var ConsentContext = createContext(null);
// Context Provider Component
export var ConsentProvider = function (_a) {
var children = _a.children;
var _b = useState({ necessary: true }), consent = _b[0], setConsent = _b[1];
// Use useCallback to memoize the function and prevent unnecessary re-renders
var updateConsent = useCallback(function (newConsent) {
setConsent(newConsent);
}, []);
return (_jsx(ConsentContext.Provider, { value: { consent: consent, updateConsent: updateConsent }, children: children }));
};
// Hook
export var useConsent = function (requiredCategories) {
if (requiredCategories === void 0) { requiredCategories = []; }
var context = useContext(ConsentContext);
if (!context) {
throw new Error('useConsent must be used within a ConsentProvider');
}
return context;
};