0
# React Hooks
1
2
Modern React hooks interface for accessing and modifying cookies in functional components with automatic re-rendering on cookie changes.
3
4
## Capabilities
5
6
### useCookies Hook
7
8
Hook for accessing and modifying cookies with automatic component re-rendering when specified cookies change.
9
10
```typescript { .api }
11
/**
12
* Hook for accessing and modifying cookies
13
* @param dependencies - Optional array of cookie names to watch for changes
14
* @param options - Optional configuration for cookie retrieval
15
* @returns Tuple containing [cookies, setCookie, removeCookie, updateCookies]
16
*/
17
function useCookies<T extends string, U = { [K in T]?: any }>(
18
dependencies?: T[],
19
options?: CookieGetOptions,
20
): [
21
U, // cookies object
22
(name: T, value: Cookie, options?: CookieSetOptions) => void, // setCookie
23
(name: T, options?: CookieSetOptions) => void, // removeCookie
24
() => void, // updateCookies
25
];
26
```
27
28
**Parameters:**
29
- `dependencies` (optional): Array of cookie names that trigger re-renders when changed. If omitted, component re-renders on any cookie change.
30
- `options` (optional): Configuration options for cookie retrieval.
31
32
**Returns:**
33
- `[0] cookies`: Object containing current cookie values, keyed by cookie name
34
- `[1] setCookie`: Function to set a cookie value
35
- `[2] removeCookie`: Function to remove a cookie
36
- `[3] updateCookies`: Function to manually refresh cookies from browser
37
38
**Usage Examples:**
39
40
```typescript
41
import React from 'react';
42
import { useCookies } from 'react-cookie';
43
44
// Basic usage - watch all cookies
45
function BasicExample() {
46
const [cookies, setCookie, removeCookie] = useCookies();
47
48
return (
49
<div>
50
<p>All cookies: {JSON.stringify(cookies)}</p>
51
<button onClick={() => setCookie('test', 'value')}>Set Cookie</button>
52
<button onClick={() => removeCookie('test')}>Remove Cookie</button>
53
</div>
54
);
55
}
56
57
// Dependency-based usage - only re-render for specific cookies
58
function DependencyExample() {
59
const [cookies, setCookie, removeCookie] = useCookies(['username', 'theme']);
60
61
return (
62
<div>
63
<p>Username: {cookies.username}</p>
64
<p>Theme: {cookies.theme}</p>
65
<button onClick={() => setCookie('username', 'john')}>Set Username</button>
66
<button onClick={() => setCookie('irrelevant', 'data')}>
67
Set Irrelevant Cookie (won't trigger re-render)
68
</button>
69
</div>
70
);
71
}
72
73
// With type safety
74
interface UserCookies {
75
username?: string;
76
userId?: string;
77
preferences?: object;
78
}
79
80
function TypedExample() {
81
const [cookies, setCookie, removeCookie] = useCookies<keyof UserCookies, UserCookies>(
82
['username', 'userId', 'preferences']
83
);
84
85
// cookies is now typed as UserCookies
86
const username: string | undefined = cookies.username;
87
88
const handleSetPreferences = () => {
89
setCookie('preferences', { theme: 'dark', language: 'en' });
90
};
91
92
return <div>{/* component JSX */}</div>;
93
}
94
95
// With cookie options
96
function OptionsExample() {
97
const [cookies, setCookie, removeCookie] = useCookies(['session'], {
98
doNotParse: true // Always return raw string values
99
});
100
101
const handleSetSession = () => {
102
setCookie('session', 'abc123', {
103
expires: new Date(Date.now() + 86400000), // 24 hours
104
secure: true,
105
httpOnly: false,
106
sameSite: 'strict',
107
path: '/'
108
});
109
};
110
111
return <div>{/* component JSX */}</div>;
112
}
113
```
114
115
### setCookie Function
116
117
Function returned by `useCookies` to set cookie values with optional configuration.
118
119
```typescript { .api }
120
/**
121
* Set a cookie value with optional configuration
122
* @param name - Cookie name
123
* @param value - Cookie value (string or object, objects are JSON-stringified)
124
* @param options - Cookie configuration options
125
*/
126
(name: T, value: Cookie, options?: CookieSetOptions) => void;
127
```
128
129
### removeCookie Function
130
131
Function returned by `useCookies` to remove cookies.
132
133
```typescript { .api }
134
/**
135
* Remove a cookie
136
* @param name - Cookie name to remove
137
* @param options - Cookie options (must match path/domain used when setting)
138
*/
139
(name: T, options?: CookieSetOptions) => void;
140
```
141
142
### updateCookies Function
143
144
Function returned by `useCookies` to manually refresh cookies from the browser.
145
146
```typescript { .api }
147
/**
148
* Manually refresh cookies from browser storage
149
* Typically not needed as the library automatically detects changes
150
*/
151
() => void;
152
```
153
154
## Hook Options
155
156
```typescript { .api }
157
interface CookieGetOptions {
158
/** Do not parse cookie values as JSON objects, return raw strings */
159
doNotParse?: boolean;
160
/** Do not update cookies when component mounts */
161
doNotUpdate?: boolean;
162
}
163
```
164
165
**Usage with options:**
166
167
```typescript
168
const [cookies, setCookie, removeCookie] = useCookies(['data'], {
169
doNotParse: true, // Always return string values, never parse JSON
170
doNotUpdate: false // Update cookies on component mount (default behavior)
171
});
172
```