0
# React Hot Toast
1
2
React Hot Toast is a lightweight React notification library that provides beautiful, customizable toast notifications with excellent performance and developer experience. It offers both a complete UI solution and headless hooks for custom implementations, handling animations, positioning, and state management automatically.
3
4
## Package Information
5
6
- **Package Name**: react-hot-toast
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-hot-toast`
10
11
## Core Imports
12
13
```typescript
14
import toast, { Toaster } from "react-hot-toast";
15
```
16
17
For headless usage:
18
19
```typescript
20
import toast, { useToaster, useToasterStore } from "react-hot-toast/headless";
21
```
22
23
CommonJS:
24
25
```javascript
26
const toast = require("react-hot-toast");
27
const { Toaster } = require("react-hot-toast");
28
```
29
30
## Basic Usage
31
32
```typescript
33
import toast, { Toaster } from "react-hot-toast";
34
35
function App() {
36
const notify = () => toast('Here is your toast.');
37
38
return (
39
<div>
40
<button onClick={notify}>Make me a toast</button>
41
<Toaster />
42
</div>
43
);
44
}
45
```
46
47
## Architecture
48
49
React Hot Toast is built around several key components:
50
51
- **Toast Function**: Main API (`toast()`) with method variants for different types
52
- **Promise API**: Automatic loading states that update based on promise resolution
53
- **UI Components**: `Toaster` container, `ToastBar` display, and icon components
54
- **Headless Hooks**: `useToaster` and `useToasterStore` for custom implementations
55
- **State Management**: Internal store handling toast lifecycle, positioning, and animations
56
- **Multi-Toaster Support**: Independent toaster instances with separate state
57
58
## Capabilities
59
60
### Basic Toast Creation
61
62
Core toast creation functions for displaying notifications with different types and styling.
63
64
```typescript { .api }
65
/**
66
* Creates a basic toast notification
67
* @param message - Content to display (string, JSX, or function)
68
* @param options - Toast configuration options
69
* @returns Toast ID string for dismissal/updates
70
*/
71
function toast(message: Renderable, options?: ToastOptions): string;
72
73
/**
74
* Creates a success toast with checkmark icon
75
* @param message - Content to display
76
* @param options - Toast configuration options
77
* @returns Toast ID string
78
*/
79
toast.success(message: Renderable, options?: ToastOptions): string;
80
81
/**
82
* Creates an error toast with error icon
83
* @param message - Content to display
84
* @param options - Toast configuration options
85
* @returns Toast ID string
86
*/
87
toast.error(message: Renderable, options?: ToastOptions): string;
88
89
/**
90
* Creates a loading toast with spinning loader
91
* @param message - Content to display
92
* @param options - Toast configuration options
93
* @returns Toast ID string
94
*/
95
toast.loading(message: Renderable, options?: ToastOptions): string;
96
97
/**
98
* Creates a custom toast with user-provided content
99
* @param message - Custom content (typically JSX)
100
* @param options - Toast configuration options
101
* @returns Toast ID string
102
*/
103
toast.custom(message: Renderable, options?: ToastOptions): string;
104
```
105
106
### Promise-Based Loading States
107
108
Automatic toast updates based on promise resolution, perfect for API calls and async operations.
109
110
```typescript { .api }
111
/**
112
* Creates a loading toast that automatically updates based on promise resolution
113
* @param promise - Promise to track or function returning promise
114
* @param messages - Messages for different states
115
* @param options - Toast configuration with per-state overrides
116
* @returns The original promise for chaining
117
*/
118
toast.promise<T>(
119
promise: Promise<T> | (() => Promise<T>),
120
messages: {
121
loading: Renderable;
122
success?: ValueOrFunction<Renderable, T>;
123
error?: ValueOrFunction<Renderable, any>;
124
},
125
options?: DefaultToastOptions
126
): Promise<T>;
127
```
128
129
**Usage Examples:**
130
131
```typescript
132
// Basic promise toast
133
const myPromise = fetch('/api/data');
134
toast.promise(myPromise, {
135
loading: 'Loading...',
136
success: 'Data loaded successfully!',
137
error: 'Failed to load data'
138
});
139
140
// Dynamic messages based on result
141
toast.promise(
142
saveUser(userData),
143
{
144
loading: 'Saving user...',
145
success: (user) => `Successfully saved ${user.name}!`,
146
error: (err) => `Error: ${err.message}`
147
}
148
);
149
```
150
151
### Toast Management
152
153
Functions for dismissing and removing toasts from the display.
154
155
```typescript { .api }
156
/**
157
* Dismisses a toast or all toasts with animation
158
* @param toastId - ID of toast to dismiss (optional, dismisses all if not provided)
159
* @param toasterId - Target specific toaster instance (optional)
160
*/
161
toast.dismiss(toastId?: string, toasterId?: string): void;
162
163
/**
164
* Dismisses all toasts in specified or all toasters
165
* @param toasterId - Target specific toaster instance (optional)
166
*/
167
toast.dismissAll(toasterId?: string): void;
168
169
/**
170
* Immediately removes a toast without animation
171
* @param toastId - ID of toast to remove (optional, removes all if not provided)
172
* @param toasterId - Target specific toaster instance (optional)
173
*/
174
toast.remove(toastId?: string, toasterId?: string): void;
175
176
/**
177
* Immediately removes all toasts without animation
178
* @param toasterId - Target specific toaster instance (optional)
179
*/
180
toast.removeAll(toasterId?: string): void;
181
```
182
183
### UI Components
184
185
React components for rendering toasts with built-in styling and animations.
186
187
```typescript { .api }
188
/**
189
* Main container component that renders all toasts
190
* @param props - Toaster configuration
191
*/
192
function Toaster(props: ToasterProps): JSX.Element;
193
194
interface ToasterProps {
195
/** Position for all toasts (default: 'top-center') */
196
position?: ToastPosition;
197
/** Default options applied to all toasts */
198
toastOptions?: DefaultToastOptions;
199
/** Render toasts in reverse order (newest at bottom) */
200
reverseOrder?: boolean;
201
/** Space between toasts in pixels (default: 8) */
202
gutter?: number;
203
/** Custom styles for the container */
204
containerStyle?: React.CSSProperties;
205
/** CSS class for the container */
206
containerClassName?: string;
207
/** Unique identifier for this toaster instance */
208
toasterId?: string;
209
/** Render function for custom toast components */
210
children?: (toast: Toast) => React.ReactElement;
211
}
212
213
/**
214
* Default toast bar component with styling and animations
215
* @param props - Toast bar configuration
216
*/
217
function ToastBar(props: ToastBarProps): JSX.Element;
218
219
interface ToastBarProps {
220
/** Toast object to render */
221
toast: Toast;
222
/** Position override for this toast */
223
position?: ToastPosition;
224
/** Custom styles for the toast bar */
225
style?: React.CSSProperties;
226
/** Render function for custom content */
227
children?: (components: {
228
icon: Renderable;
229
message: Renderable;
230
}) => Renderable;
231
}
232
233
/**
234
* Icon component with animations for different toast types
235
* @param props - Icon configuration
236
*/
237
function ToastIcon(props: { toast: Toast }): JSX.Element;
238
```
239
240
### Icon Components
241
242
Animated icon components for different toast states.
243
244
```typescript { .api }
245
/**
246
* Animated checkmark icon for success toasts
247
*/
248
function CheckmarkIcon(props: CheckmarkTheme): JSX.Element;
249
250
interface CheckmarkTheme {
251
/** Primary color (default: '#61d345') */
252
primary?: string;
253
/** Secondary color (default: '#fff') */
254
secondary?: string;
255
}
256
257
/**
258
* Animated error icon for error toasts
259
*/
260
function ErrorIcon(props: ErrorTheme): JSX.Element;
261
262
interface ErrorTheme {
263
/** Primary color (default: '#ff4b4b') */
264
primary?: string;
265
/** Secondary color (default: '#fff') */
266
secondary?: string;
267
}
268
269
/**
270
* Animated loader icon for loading toasts
271
*/
272
function LoaderIcon(props: LoaderTheme): JSX.Element;
273
274
interface LoaderTheme {
275
/** Primary color (default: '#616161') */
276
primary?: string;
277
/** Secondary color (default: '#e0e0e0') */
278
secondary?: string;
279
}
280
```
281
282
### Headless Hooks
283
284
React hooks for custom toast implementations without built-in UI components.
285
286
```typescript { .api }
287
/**
288
* Main hook for managing toast state and handlers
289
* @param toastOptions - Default options for all toasts
290
* @param toasterId - Unique identifier for this toaster instance (default: 'default')
291
* @returns Toast state and handler functions
292
*/
293
function useToaster(
294
toastOptions?: DefaultToastOptions,
295
toasterId?: string
296
): {
297
toasts: Toast[];
298
handlers: {
299
updateHeight: (toastId: string, height: number) => void;
300
startPause: () => void;
301
endPause: () => void;
302
calculateOffset: (
303
toast: Toast,
304
opts?: {
305
reverseOrder?: boolean;
306
gutter?: number;
307
defaultPosition?: ToastPosition;
308
}
309
) => number;
310
};
311
};
312
313
/**
314
* Hook for accessing raw toast store state
315
* @param toastOptions - Default options for merging with toast state
316
* @param toasterId - Unique identifier for this toaster instance
317
* @returns Current toaster state
318
*/
319
function useToasterStore(
320
toastOptions?: DefaultToastOptions,
321
toasterId?: string
322
): ToasterState;
323
324
interface ToasterState {
325
/** Array of current toasts */
326
toasts: Toast[];
327
/** Toaster configuration settings */
328
settings: ToasterSettings;
329
/** Timestamp when toasts were paused (undefined if not paused) */
330
pausedAt: number | undefined;
331
}
332
333
/** Toaster configuration settings */
334
interface ToasterSettings {
335
/** Maximum number of toasts to show simultaneously */
336
toastLimit: number;
337
}
338
```
339
340
### Utility Functions
341
342
Helper functions for working with dynamic values and toast state.
343
344
```typescript { .api }
345
/**
346
* Resolves a value or function to its final value
347
* @param valOrFunction - Static value or function that returns value
348
* @param arg - Argument passed to function if valOrFunction is a function
349
* @returns Resolved value
350
*/
351
function resolveValue<TValue, TArg>(
352
valOrFunction: ValueOrFunction<TValue, TArg>,
353
arg: TArg
354
): TValue;
355
```
356
357
## Types
358
359
### Core Types
360
361
```typescript { .api }
362
/** Content that can be rendered in a toast */
363
type Renderable = React.ReactElement | string | null;
364
365
/** Toast type determining icon and default styling */
366
type ToastType = 'success' | 'error' | 'loading' | 'blank' | 'custom';
367
368
/** Available positions for toast placement */
369
type ToastPosition =
370
| 'top-left'
371
| 'top-center'
372
| 'top-right'
373
| 'bottom-left'
374
| 'bottom-center'
375
| 'bottom-right';
376
377
/** Function that receives an argument and returns a value */
378
type ValueFunction<TValue, TArg> = (arg: TArg) => TValue;
379
380
/** Either a static value or a function that returns the value */
381
type ValueOrFunction<TValue, TArg> = TValue | ValueFunction<TValue, TArg>;
382
383
/** Message content type used internally */
384
type Message = ValueOrFunction<Renderable, Toast>;
385
386
/** Complete toast object with all properties */
387
interface Toast {
388
/** Toast type determining appearance */
389
type: ToastType;
390
/** Unique identifier */
391
id: string;
392
/** Toaster instance this toast belongs to */
393
toasterId?: string;
394
/** Content to display (can be dynamic based on toast state) */
395
message: ValueOrFunction<Renderable, Toast>;
396
/** Custom icon override */
397
icon?: Renderable;
398
/** How long to show before auto-dismiss (ms, Infinity for manual) */
399
duration?: number;
400
/** Accumulated pause time (internal) */
401
pauseDuration: number;
402
/** Position override for this toast */
403
position?: ToastPosition;
404
/** Delay before removing from DOM after dismissal */
405
removeDelay?: number;
406
/** Accessibility attributes */
407
ariaProps: {
408
role: 'status' | 'alert';
409
'aria-live': 'assertive' | 'off' | 'polite';
410
};
411
/** Custom CSS styles */
412
style?: React.CSSProperties;
413
/** CSS class name */
414
className?: string;
415
/** Icon color theme */
416
iconTheme?: IconTheme;
417
/** Creation timestamp */
418
createdAt: number;
419
/** Whether toast is currently visible */
420
visible: boolean;
421
/** Whether toast has been dismissed */
422
dismissed: boolean;
423
/** Calculated height for positioning (internal) */
424
height?: number;
425
}
426
427
/** Configuration options for individual toasts */
428
type ToastOptions = Partial<Pick<
429
Toast,
430
| 'id'
431
| 'icon'
432
| 'duration'
433
| 'ariaProps'
434
| 'className'
435
| 'style'
436
| 'position'
437
| 'iconTheme'
438
| 'toasterId'
439
| 'removeDelay'
440
>>;
441
442
/** Default options with per-type overrides */
443
type DefaultToastOptions = ToastOptions & {
444
[key in ToastType]?: ToastOptions;
445
};
446
447
/** Icon color theme */
448
interface IconTheme {
449
/** Primary color */
450
primary: string;
451
/** Secondary color */
452
secondary: string;
453
}
454
```
455
456
### Internal Types
457
458
```typescript { .api }
459
/** Internal wrapper props for toast positioning */
460
interface ToastWrapperProps {
461
/** Toast unique identifier */
462
id: string;
463
/** CSS class name */
464
className?: string;
465
/** Custom styles */
466
style?: React.CSSProperties;
467
/** Callback when toast height changes */
468
onHeightUpdate: (id: string, height: number) => void;
469
/** Toast content */
470
children?: React.ReactNode;
471
}
472
473
/** Toaster configuration settings */
474
interface ToasterSettings {
475
/** Maximum number of toasts to show simultaneously */
476
toastLimit: number;
477
}
478
```
479
480
## Configuration
481
482
### Default Durations
483
484
React Hot Toast uses different default durations based on toast type:
485
486
- **success**: 2000ms (2 seconds)
487
- **error**: 4000ms (4 seconds)
488
- **loading**: Infinity (manual dismissal)
489
- **blank**: 4000ms (4 seconds)
490
- **custom**: 4000ms (4 seconds)
491
492
493
## Advanced Usage Examples
494
495
### Custom Toast Component
496
497
```typescript
498
import { Toaster } from "react-hot-toast";
499
500
function CustomToaster() {
501
return (
502
<Toaster>
503
{(t) => (
504
<div
505
className={`${
506
t.visible ? 'animate-enter' : 'animate-leave'
507
} custom-toast`}
508
>
509
<div>{t.message}</div>
510
<button onClick={() => toast.dismiss(t.id)}>×</button>
511
</div>
512
)}
513
</Toaster>
514
);
515
}
516
```
517
518
### Multiple Toaster Instances
519
520
```typescript
521
// Different toasters for different areas
522
toast('Global notification');
523
toast('Header notification', { toasterId: 'header' });
524
525
// Render toasters
526
<Toaster /> {/* Default toaster */}
527
<Toaster toasterId="header" position="top-right" />
528
```
529
530
### Headless Implementation
531
532
```typescript
533
import { useToaster } from "react-hot-toast/headless";
534
535
function CustomToastContainer() {
536
const { toasts, handlers } = useToaster();
537
538
return (
539
<div
540
onMouseEnter={handlers.startPause}
541
onMouseLeave={handlers.endPause}
542
>
543
{toasts.map((toast) => (
544
<div
545
key={toast.id}
546
style={{
547
transform: `translateY(${handlers.calculateOffset(toast)}px)`
548
}}
549
>
550
{typeof toast.message === 'function'
551
? toast.message(toast)
552
: toast.message}
553
</div>
554
))}
555
</div>
556
);
557
}
558
```