Comprehensive React hooks for client-side cookie management including both static and reactive variants. Static hooks provide direct access to cookie functions, while reactive hooks offer real-time cookie state management through a context provider.
Static hooks wrap the basic cookie functions for use in React components. They handle mounting state to prevent hydration mismatches.
Returns a function to get all cookies, properly wrapped for React lifecycle.
/**
* Hook that returns a function to get all cookies
* @returns Function to retrieve all cookies, returns empty function until mounted
*/
function useGetCookies(): () => TmpCookiesObj | undefined;Usage Examples:
import { useGetCookies } from 'cookies-next/client';
function CookieList() {
const getCookies = useGetCookies();
const handleShowCookies = () => {
const allCookies = getCookies();
console.log('All cookies:', allCookies);
};
return <button onClick={handleShowCookies}>Show All Cookies</button>;
}Returns a function to get a specific cookie by key.
/**
* Hook that returns a function to get a specific cookie
* @returns Function to retrieve cookie by key
*/
function useGetCookie(): (key: string, options?: OptionsType) => CookieValueTypes;Usage Examples:
import { useGetCookie } from 'cookies-next/client';
function UserGreeting() {
const getCookie = useGetCookie();
const handleGreet = () => {
const username = getCookie('username');
alert(username ? `Hello, ${username}!` : 'Hello, guest!');
};
return <button onClick={handleGreet}>Greet User</button>;
}Returns a function to set cookies.
/**
* Hook that returns a function to set cookies
* @returns Function to set cookie with key, value, and options
*/
function useSetCookie(): (key: string, data: any, options?: OptionsType) => void;Usage Examples:
import { useSetCookie } from 'cookies-next/client';
function ThemeSelector() {
const setCookie = useSetCookie();
const handleThemeChange = (theme: string) => {
setCookie('theme', theme, {
maxAge: 365 * 24 * 60 * 60, // 1 year
sameSite: 'strict'
});
};
return (
<div>
<button onClick={() => handleThemeChange('light')}>Light Theme</button>
<button onClick={() => handleThemeChange('dark')}>Dark Theme</button>
</div>
);
}Returns a function to delete cookies.
/**
* Hook that returns a function to delete cookies
* @returns Function to delete cookie by key
*/
function useDeleteCookie(): (key: string, options?: OptionsType) => void;Usage Examples:
import { useDeleteCookie } from 'cookies-next/client';
function LogoutButton() {
const deleteCookie = useDeleteCookie();
const handleLogout = () => {
deleteCookie('auth-token');
deleteCookie('user-id');
deleteCookie('session-data');
window.location.href = '/login';
};
return <button onClick={handleLogout}>Logout</button>;
}Returns a function to check if a cookie exists.
/**
* Hook that returns a function to check cookie existence
* @returns Function to check if cookie exists by key
*/
function useHasCookie(): (key: string, options?: OptionsType) => boolean;Usage Examples:
import { useHasCookie } from 'cookies-next/client';
function WelcomeMessage() {
const hasCookie = useHasCookie();
const showWelcome = () => {
const isFirstVisit = !hasCookie('visited-before');
if (isFirstVisit) {
// Show welcome modal or tutorial
console.log('Welcome new user!');
}
};
return <button onClick={showWelcome}>Check First Visit</button>;
}Returns an object with all basic cookie operations for convenience.
/**
* Hook that returns an object with all cookie operations
* @returns Object containing all cookie function wrappers
*/
function useCookiesNext(): CookiesNextHookResult;
interface CookiesNextHookResult {
getCookies: () => TmpCookiesObj | undefined;
getCookie: (key: string, options?: OptionsType) => CookieValueTypes;
setCookie: (key: string, data: any, options?: OptionsType) => void;
deleteCookie: (key: string, options?: OptionsType) => void;
hasCookie: (key: string, options?: OptionsType) => boolean;
}Usage Examples:
import { useCookiesNext } from 'cookies-next/client';
function CookieManager() {
const { getCookie, setCookie, deleteCookie, hasCookie } = useCookiesNext();
const handleSavePreference = (key: string, value: string) => {
setCookie(key, value, { maxAge: 30 * 24 * 60 * 60 });
};
const handleLoadPreference = (key: string) => {
return getCookie(key) || 'default';
};
const handleClearPreference = (key: string) => {
if (hasCookie(key)) {
deleteCookie(key);
}
};
return (
<div>
<button onClick={() => handleSavePreference('color', 'blue')}>
Save Color Preference
</button>
<button onClick={() => console.log(handleLoadPreference('color'))}>
Load Color Preference
</button>
<button onClick={() => handleClearPreference('color')}>
Clear Color Preference
</button>
</div>
);
}Reactive hooks provide real-time cookie state management through a context provider. They automatically update when cookies change and require the CookiesNextProvider.
Context provider component that enables reactive cookie state management with optional polling.
/**
* Context provider for reactive cookie management
* @param children - React children components
* @param pollingOptions - Configuration for cookie change polling
*/
function CookiesNextProvider({
children,
pollingOptions
}: {
children: ReactNode;
pollingOptions?: PollingOptions;
}): JSX.Element;
type PollingOptions = {
enabled?: boolean;
intervalMs?: number;
};Usage Examples:
import { CookiesNextProvider } from 'cookies-next/client';
// Basic provider setup
function App({ children }) {
return (
<CookiesNextProvider>
{children}
</CookiesNextProvider>
);
}
// Provider with polling enabled
function AppWithPolling({ children }) {
return (
<CookiesNextProvider
pollingOptions={{
enabled: true,
intervalMs: 1000 // Check for changes every second
}}
>
{children}
</CookiesNextProvider>
);
}Returns a function that provides reactive access to all cookies from context state.
/**
* Hook that returns a function to get all cookies from reactive context
* @returns Function to retrieve all cookies from context state
*/
function useReactiveGetCookies(): (options?: OptionsType) => TmpCookiesObj | undefined;Usage Examples:
import { useReactiveGetCookies, CookiesNextProvider } from 'cookies-next/client';
function CookieDisplay() {
const getCookies = useReactiveGetCookies();
const allCookies = getCookies();
return (
<div>
<h3>Current Cookies:</h3>
<pre>{JSON.stringify(allCookies, null, 2)}</pre>
</div>
);
}
function App() {
return (
<CookiesNextProvider>
<CookieDisplay />
</CookiesNextProvider>
);
}Returns a function that provides reactive access to a specific cookie value.
/**
* Hook that returns a function to get a specific cookie from reactive context
* @returns Function to retrieve cookie value from context state
*/
function useReactiveGetCookie(): (key: string, options?: OptionsType) => CookieValueTypes;Usage Examples:
import { useReactiveGetCookie, CookiesNextProvider } from 'cookies-next/client';
function UserProfile() {
const getCookie = useReactiveGetCookie();
const username = getCookie('username');
const theme = getCookie('theme') || 'light';
return (
<div data-theme={theme}>
<h1>Welcome, {username || 'Guest'}!</h1>
</div>
);
}
function App() {
return (
<CookiesNextProvider>
<UserProfile />
</CookiesNextProvider>
);
}Returns a function that sets cookies and updates the reactive context state.
/**
* Hook that returns a function to set cookies with context state updates
* @returns Function to set cookie and update context
*/
function useReactiveSetCookie(): (key: string, data: any, options?: OptionsType) => void;Usage Examples:
import { useReactiveSetCookie, useReactiveGetCookie, CookiesNextProvider } from 'cookies-next/client';
function ThemeToggle() {
const getCookie = useReactiveGetCookie();
const setCookie = useReactiveSetCookie();
const currentTheme = getCookie('theme') || 'light';
const toggleTheme = () => {
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
setCookie('theme', newTheme, { maxAge: 365 * 24 * 60 * 60 });
};
return (
<button onClick={toggleTheme}>
Current theme: {currentTheme}
</button>
);
}
function App() {
return (
<CookiesNextProvider>
<ThemeToggle />
</CookiesNextProvider>
);
}Returns a function that deletes cookies and updates the reactive context state.
/**
* Hook that returns a function to delete cookies with context state updates
* @returns Function to delete cookie and update context
*/
function useReactiveDeleteCookie(): (key: string, options?: OptionsType) => void;Usage Examples:
import {
useReactiveDeleteCookie,
useReactiveGetCookie,
CookiesNextProvider
} from 'cookies-next/client';
function SessionManager() {
const getCookie = useReactiveGetCookie();
const deleteCookie = useReactiveDeleteCookie();
const sessionToken = getCookie('session-token');
const handleLogout = () => {
deleteCookie('session-token');
deleteCookie('user-data');
};
return (
<div>
{sessionToken ? (
<button onClick={handleLogout}>Logout</button>
) : (
<p>Not logged in</p>
)}
</div>
);
}Returns a function that reactively checks if a cookie exists.
/**
* Hook that returns a function to check cookie existence from reactive context
* @returns Function to check if cookie exists in context state
*/
function useReactiveHasCookie(): (key: string, options?: OptionsType) => boolean;Usage Examples:
import { useReactiveHasCookie, CookiesNextProvider } from 'cookies-next/client';
function ConditionalContent() {
const hasCookie = useReactiveHasCookie();
const hasSeenWelcome = hasCookie('welcome-seen');
return (
<div>
{!hasSeenWelcome && <WelcomeModal />}
<MainContent />
</div>
);
}Returns a function to manually trigger cookie state revalidation in the reactive context.
/**
* Hook that returns a function to manually revalidate cookie state
* @returns Function to force cookie state refresh from document.cookie
*/
function useRevalidateCookiesState(): () => void;Usage Examples:
import { useRevalidateCookiesState, CookiesNextProvider } from 'cookies-next/client';
function CookieManager() {
const revalidate = useRevalidateCookiesState();
const handleExternalCookieChange = () => {
// Some external code changed cookies
document.cookie = 'external=value; path=/';
// Force context to update
revalidate();
};
return <button onClick={handleExternalCookieChange}>Update External Cookie</button>;
}Returns an object with all reactive cookie operations.
/**
* Hook that returns an object with all reactive cookie operations
* @returns Object containing all reactive cookie functions and state management
*/
function useReactiveCookiesNext(): ReactiveCookiesNextHookResult;
interface ReactiveCookiesNextHookResult {
getCookies: (options?: OptionsType) => TmpCookiesObj | undefined;
getCookie: (key: string, options?: OptionsType) => CookieValueTypes;
setCookie: (key: string, data: any, options?: OptionsType) => void;
deleteCookie: (key: string, options?: OptionsType) => void;
hasCookie: (key: string, options?: OptionsType) => boolean;
revalidateCookiesState: () => void;
}Usage Examples:
import { useReactiveCookiesNext, CookiesNextProvider } from 'cookies-next/client';
function AdvancedCookieManager() {
const {
getCookie,
setCookie,
deleteCookie,
hasCookie,
revalidateCookiesState
} = useReactiveCookiesNext();
const currentUser = getCookie('current-user');
const hasPreferences = hasCookie('user-preferences');
const handleSaveUser = (userData: any) => {
setCookie('current-user', JSON.stringify(userData));
if (!hasPreferences) {
setCookie('user-preferences', JSON.stringify({ theme: 'light' }));
}
};
const handleClearAll = () => {
deleteCookie('current-user');
deleteCookie('user-preferences');
revalidateCookiesState(); // Force state refresh
};
return (
<div>
<p>Current user: {currentUser || 'None'}</p>
<p>Has preferences: {hasPreferences ? 'Yes' : 'No'}</p>
<button onClick={() => handleSaveUser({ name: 'Alice', id: 123 })}>
Save User
</button>
<button onClick={handleClearAll}>Clear All</button>
</div>
);
}
function App() {
return (
<CookiesNextProvider pollingOptions={{ enabled: true, intervalMs: 500 }}>
<AdvancedCookieManager />
</CookiesNextProvider>
);
}Hook for polling cookie changes at specified intervals, primarily used internally by the reactive system but available for custom implementations.
/**
* Hook for polling cookie changes at specified intervals
* @param onChange - Callback function called when cookies change
* @param pollingOptions - Configuration for polling behavior
*/
function useCookiesPolling(
onChange: (newCookies: TmpCookiesObj | undefined) => void,
pollingOptions?: PollingOptions
): void;Usage Examples:
import { useCookiesPolling, getCookies } from 'cookies-next/client';
import { useState } from 'react';
function CustomCookieMonitor() {
const [cookieCount, setCookieCount] = useState(0);
useCookiesPolling((newCookies) => {
if (newCookies) {
setCookieCount(Object.keys(newCookies).length);
}
}, {
enabled: true,
intervalMs: 2000 // Check every 2 seconds
});
return <div>Cookie count: {cookieCount}</div>;
}All hooks handle server-side rendering and hydration properly:
import { useGetCookie } from 'cookies-next/client';
import { useEffect, useState } from 'react';
function HydrationSafeComponent() {
const getCookie = useGetCookie();
const [theme, setTheme] = useState('light');
useEffect(() => {
// Only access cookies after hydration
const savedTheme = getCookie('theme');
if (savedTheme) {
setTheme(savedTheme);
}
}, [getCookie]);
return <div data-theme={theme}>Content</div>;
}Wrap cookie operations in error boundaries for robust applications:
import { useSetCookie } from 'cookies-next/client';
function SafeCookieComponent() {
const setCookie = useSetCookie();
const handleSaveCookie = () => {
try {
setCookie('data', 'value', {
secure: true,
sameSite: 'strict'
});
} catch (error) {
console.error('Failed to set cookie:', error);
}
};
return <button onClick={handleSaveCookie}>Save Cookie</button>;
}