GitHub

useToaster() API

Create your own notification system with headless mode. The useToaster() hook will manage the notification state for you. This includes keeping track of all toast created with toast(), auto-dimiss, pause on hover and an unmount delay for exit animations. The hook will provide you with the current state, so you can render on own components. Tree shaking is supported, so you won't ship any unused styles from library.

It's recommended to only have one <Toaster/> or useToaster() in your app at a time. If you need the current state without the handlers, you should use useToasterStore() instead.

Usage with React Native

Headless mode is perfectly suited to add notifications to your React Native app. You can check out this example.

Examples

Basic Example

const Notifications = () => {
const { visibleToasts, handlers } = useToaster();
const { startPause, endPause } = handlers;
return (
<div onMouseEnter={startPause} onMouseLeave={endPause}>
{visibleToasts.map((toast) => (
<div key={toast.id} role={toast.role} aria-live={toast.ariaLive}>
{toast.message}
</div>
))}
</div>
);
};
// Create toasts anywhere
toast('Hello World');

Animated Example

Instead of mapping over visibleToasts we'll use toasts, which includes all hidden toasts aswell. We animate them based on toast.visible. Toasts will be removed from 1 second after being dismissed, which give us enough time to animate.

You can play with the demo on CodeSandbox.

import { useToaster } from 'react-hot-toast';
const Notifications = () => {
const { toasts, handlers } = useToaster();
const { startPause, endPause, calculateOffset, updateHeight } = handlers;
return (
<div
style={{
position: 'fixed',
top: 8,
left: 8,
}}
onMouseEnter={startPause}
onMouseLeave={endPause}
>
{toasts.map((toast) => {
const offset = calculateOffset(toast.id, {
reverseOrder: false,
margin: 8,
});
const ref = (el) => {
if (el && !toast.height) {
const height = el.getBoundingClientRect().height;
updateHeight(toast.id, height);
}
};
return (
<div
key={toast.id}
ref={ref}
style={{
position: 'absolute',
width: '200px',
background: 'papayawhip',
transition: 'all 0.5s ease-out',
opacity: toast.visible ? 1 : 0,
transform: `translateY(${offset}px)`,
}}
>
{toast.message}
</div>
);
})}
</div>
);
};