0
# React Hooks
1
2
React hooks for form management, utility functions, UI state, and integration with Payload CMS admin interfaces.
3
4
## Form and Field Hooks
5
6
### useField
7
8
Get and set form field values with validation and error handling.
9
10
```typescript { .api }
11
function useField<TValue>(options?: {
12
path?: string;
13
validate?: (value: TValue) => string | true;
14
disableFormData?: boolean;
15
hasRows?: boolean;
16
potentiallyStalePath?: string;
17
}): FieldType<TValue>;
18
19
interface FieldType<TValue> {
20
value: TValue;
21
setValue: (value: TValue) => void;
22
showError: boolean;
23
errorMessage?: string;
24
valid: boolean;
25
disabled: boolean;
26
initialValue?: TValue;
27
reset: () => void;
28
validate: () => void;
29
}
30
```
31
32
Usage example:
33
```typescript
34
import { useField } from '@payloadcms/ui';
35
36
function CustomTextField() {
37
const {
38
value,
39
setValue,
40
showError,
41
errorMessage,
42
valid
43
} = useField<string>({
44
path: 'title',
45
validate: (val) => val?.length > 0 || 'Title is required'
46
});
47
48
return (
49
<div>
50
<input
51
value={value || ''}
52
onChange={(e) => setValue(e.target.value)}
53
className={showError ? 'error' : ''}
54
/>
55
{showError && <span className="error">{errorMessage}</span>}
56
</div>
57
);
58
}
59
```
60
61
### useForm
62
63
Access form-wide state and control functions.
64
65
```typescript { .api }
66
function useForm(): FormContext;
67
68
interface FormContext {
69
getData: () => Record<string, unknown>;
70
submit: () => Promise<void>;
71
reset: () => void;
72
setModified: (modified: boolean) => void;
73
validate: () => boolean;
74
addFieldRow: (path: string, rowIndex?: number) => void;
75
removeFieldRow: (path: string, rowIndex: number) => void;
76
moveFieldRow: (path: string, fromIndex: number, toIndex: number) => void;
77
}
78
```
79
80
### useDocumentForm
81
82
Access the document-level form context (useful for nested forms).
83
84
```typescript { .api }
85
function useDocumentForm(): FormContext;
86
```
87
88
### useFormFields
89
90
Get and set form field values using a selector function.
91
92
```typescript { .api }
93
function useFormFields<Value>(
94
selector: (fields: FormFieldsContextType) => Value
95
): Value;
96
97
interface FormFieldsContextType {
98
[path: string]: FieldState;
99
}
100
101
interface FieldState {
102
value: unknown;
103
valid: boolean;
104
errorMessage?: string;
105
initialValue?: unknown;
106
}
107
```
108
109
### useAllFormFields
110
111
Get the complete form fields state.
112
113
```typescript { .api }
114
function useAllFormFields(): FormFieldsContextType;
115
```
116
117
### Form State Hooks
118
119
Monitor specific aspects of form state.
120
121
```typescript { .api }
122
function useFormSubmitted(): boolean;
123
function useFormProcessing(): boolean;
124
function useFormBackgroundProcessing(): boolean;
125
function useFormModified(): boolean;
126
function useFormInitializing(): boolean;
127
```
128
129
## Utility Hooks
130
131
### usePayloadAPI
132
133
Make API requests to Payload endpoints with loading and error states.
134
135
```typescript { .api }
136
function usePayloadAPI<T>(
137
url: string,
138
options?: {
139
initialData?: T;
140
initialParams?: Record<string, unknown>;
141
}
142
): [{
143
data: T;
144
isError: boolean;
145
isLoading: boolean;
146
}, {
147
setParams: (params: Record<string, unknown>) => void;
148
}];
149
```
150
151
Usage example:
152
```typescript
153
import { usePayloadAPI } from '@payloadcms/ui';
154
155
function UserList() {
156
const [{ data: users, isLoading, isError }, { setParams }] = usePayloadAPI<User[]>(
157
'/api/users',
158
{ initialData: [] }
159
);
160
161
const handleSearch = (query: string) => {
162
setParams({ search: query });
163
};
164
165
if (isLoading) return <div>Loading...</div>;
166
if (isError) return <div>Error loading users</div>;
167
168
return (
169
<div>
170
{users.map(user => <div key={user.id}>{user.email}</div>)}
171
</div>
172
);
173
}
174
```
175
176
### useDebounce
177
178
Debounce a value with a specified delay.
179
180
```typescript { .api }
181
function useDebounce<T>(value: T, delay: number): T;
182
```
183
184
### useDebouncedCallback
185
186
Debounce a callback function.
187
188
```typescript { .api }
189
function useDebouncedCallback<Args extends unknown[]>(
190
callback: (...args: Args) => void,
191
delay: number,
192
deps?: React.DependencyList
193
): (...args: Args) => void;
194
```
195
196
### useDebouncedEffect
197
198
Run an effect with debouncing.
199
200
```typescript { .api }
201
function useDebouncedEffect(
202
callback: () => void | (() => void),
203
delay: number,
204
deps?: React.DependencyList
205
): void;
206
```
207
208
### useHotkey
209
210
Listen for keyboard shortcuts.
211
212
```typescript { .api }
213
function useHotkey(
214
options: {
215
keyCodes: string[];
216
cmdCtrlKey?: boolean;
217
editDepth?: number;
218
},
219
callback: (event: KeyboardEvent) => void
220
): void;
221
```
222
223
Usage example:
224
```typescript
225
import { useHotkey } from '@payloadcms/ui';
226
227
function DocumentEditor() {
228
useHotkey(
229
{ keyCodes: ['s'], cmdCtrlKey: true },
230
(event) => {
231
event.preventDefault();
232
handleSave();
233
}
234
);
235
236
return <div>Use Cmd/Ctrl+S to save</div>;
237
}
238
```
239
240
### useClickOutside
241
242
Detect clicks outside an element.
243
244
```typescript { .api }
245
function useClickOutside<T extends HTMLElement>(
246
ref: React.RefObject<T>,
247
callback: (event: MouseEvent) => void
248
): void;
249
```
250
251
### useDelay
252
253
Create a delayed state that becomes true after a specified delay.
254
255
```typescript { .api }
256
function useDelay(delay: number): boolean;
257
```
258
259
### useDelayedRender
260
261
Delay component rendering for a specified time.
262
263
```typescript { .api }
264
function useDelayedRender(delay: number): boolean;
265
```
266
267
### useIntersect
268
269
Intersection Observer hook for detecting element visibility.
270
271
```typescript { .api }
272
function useIntersect<T extends HTMLElement>(
273
ref: React.RefObject<T>
274
): {
275
isIntersecting: boolean;
276
entry?: IntersectionObserverEntry;
277
};
278
```
279
280
### useResize
281
282
Window resize detection hook.
283
284
```typescript { .api }
285
function useResize(): {
286
width: number;
287
height: number;
288
};
289
```
290
291
### useThrottledEffect
292
293
Throttled version of useEffect.
294
295
```typescript { .api }
296
function useThrottledEffect(
297
callback: () => void | (() => void),
298
delay: number,
299
deps?: React.DependencyList
300
): void;
301
```
302
303
## UI State Hooks
304
305
### useAuth
306
307
Access authentication state and methods.
308
309
```typescript { .api }
310
function useAuth<T = any>(): AuthContext<T>;
311
312
interface AuthContext<T> {
313
user: T | null;
314
token?: string;
315
permissions?: SanitizedPermissions;
316
logOut: () => Promise<void>;
317
refreshCookie: () => Promise<void>;
318
setUser: (user: T | null) => void;
319
strategy?: string;
320
}
321
```
322
323
### useConfig
324
325
Access Payload configuration.
326
327
```typescript { .api }
328
function useConfig(): ClientConfigContext;
329
330
interface ClientConfigContext {
331
config: ClientConfig;
332
getEntityConfig: (slug: string, type: 'collections' | 'globals') => EntityConfig;
333
setConfig: (config: ClientConfig) => void;
334
}
335
```
336
337
### useTranslation
338
339
Access translation functions.
340
341
```typescript { .api }
342
function useTranslation(): TranslationContext;
343
344
interface TranslationContext {
345
t: (key: string, options?: Record<string, unknown>) => string;
346
i18n: {
347
language: string;
348
languages: string[];
349
changeLanguage: (lang: string) => void;
350
};
351
}
352
```
353
354
### useLocale
355
356
Access current locale information.
357
358
```typescript { .api }
359
function useLocale(): LocaleContext;
360
361
interface LocaleContext {
362
locale: string;
363
setLocale: (locale: string) => void;
364
}
365
```
366
367
### useDocumentInfo
368
369
Access information about the current document.
370
371
```typescript { .api }
372
function useDocumentInfo(): DocumentInfoContext;
373
374
interface DocumentInfoContext {
375
id?: string | number;
376
collection?: string;
377
global?: string;
378
hasPublishedDoc?: boolean;
379
unpublishedVersions?: number;
380
publishedVersions?: number;
381
mostRecentVersionIsAutosaved?: boolean;
382
initialState?: Record<string, unknown>;
383
}
384
```
385
386
### useOperation
387
388
Access current CRUD operation type.
389
390
```typescript { .api }
391
function useOperation(): string; // 'create' | 'update'
392
```
393
394
### useParams
395
396
Access route parameters.
397
398
```typescript { .api }
399
function useParams(): Record<string, string>;
400
```
401
402
### usePreferences
403
404
Access and modify user preferences.
405
406
```typescript { .api }
407
function usePreferences(): PreferencesContext;
408
409
interface PreferencesContext {
410
getPreference: <T = any>(key: string) => T;
411
setPreference: <T = any>(key: string, value: T) => void;
412
}
413
```
414
415
### useTheme
416
417
Access theme configuration and switching.
418
419
```typescript { .api }
420
function useTheme(): ThemeContext;
421
422
interface ThemeContext {
423
theme: Theme;
424
setTheme: (theme: 'light' | 'dark' | 'auto') => void;
425
autoMode: boolean;
426
}
427
```
428
429
## Types
430
431
```typescript { .api }
432
interface SanitizedPermissions {
433
collections: Record<string, CollectionPermission>;
434
globals: Record<string, GlobalPermission>;
435
canAccessAdmin: boolean;
436
}
437
438
interface CollectionPermission {
439
create: boolean;
440
read: boolean;
441
update: boolean;
442
delete: boolean;
443
}
444
445
interface GlobalPermission {
446
read: boolean;
447
update: boolean;
448
}
449
450
interface ClientConfig {
451
routes: {
452
admin: string;
453
api: string;
454
};
455
collections: CollectionConfig[];
456
globals: GlobalConfig[];
457
localization?: LocalizationConfig;
458
admin: AdminConfig;
459
}
460
461
interface EntityConfig {
462
slug: string;
463
labels: {
464
singular: string;
465
plural: string;
466
};
467
fields: FieldConfig[];
468
}
469
470
interface Theme {
471
name: string;
472
colors: Record<string, string>;
473
breakpoints: Record<string, string>;
474
}
475
```