useToaster()
API
The useToaster()
hook provides you a headless system that 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.
Be aware: react-hot-toast 2.0 adds support for custom render functions, an easier method to render custom notification components.
Tree shaking is supported so that you won't ship any unused styles from the 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 { toasts, handlers } = useToaster();const { startPause, endPause } = handlers;return (<div onMouseEnter={startPause} onMouseLeave={endPause}>{toasts.filter((toast) => toast.visible).map((toast) => (<div key={toast.id} {...toast.ariaProps}>{toast.message}</div>))}</div>);};// Create toasts anywheretoast('Hello World');
Animated Example
Instead of mapping over visibleToasts
we'll use toasts
, which includes all hidden toasts. 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 (<divstyle={{position: 'fixed',top: 8,left: 8,}}onMouseEnter={startPause}onMouseLeave={endPause}>{toasts.map((toast) => {const offset = calculateOffset(toast, {reverseOrder: false,gutter: 8,});const ref = (el) => {if (el && !toast.height) {const height = el.getBoundingClientRect().height;updateHeight(toast.id, height);}};return (<divkey={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.ariaProps}>{toast.message}</div>);})}</div>);};