Toast & ToastProvider
An accessible, animated toast notification system built for React and Next.js applications. Supports semantic visual variants, stacked layouts, auto-dismiss with pause-on-hover, SSR-friendly portals, and dual dispatch APIs: hook-based (useToast) and zero-JSX imperative notifications (nui.toast, nui.success, nui.error).
import { ToastProvider, useToast, nui } from '@nofinite/nui';Interactive Preview
Setup
Mount <ToastProvider> once at the root of your application (e.g. inside app/layout.tsx):
// app/layout.tsx (Next.js App Router)
import { ToastProvider } from '@nofinite/nui';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ToastProvider>
{children}
</ToastProvider>
</body>
</html>
);
}Dual Usage Patterns
NUI provides two complementary ways to trigger notifications:
1. Hook-Based (useToast)
Use inside any React component within the <ToastProvider> tree:
'use client';
import { Button, useToast } from '@nofinite/nui';
export function SaveButton() {
const toast = useToast();
const handleSave = () => {
toast.show('Settings saved successfully', {
variant: 'success',
description: 'Your changes have been synced across all devices.',
duration: 5000,
});
};
return (
<Button variant="primary" onClick={handleSave}>
Save Changes
</Button>
);
}2. Zero-JSX Imperative (nui.*)
Trigger toasts directly from event handlers, API interceptors, or utility functions without needing React hooks or component context:
import { nui } from '@nofinite/nui';
// In an API response handler or client utility:
async function updateProfile(data) {
try {
await api.post('/profile', data);
nui.success('Profile updated successfully!');
} catch (err) {
nui.error('Failed to update profile. Please try again.');
}
}Semantic Variants
Toasts use semantic design tokens for instant visual hierarchy:
| Variant | Token Accent | Typical Use Case |
|---|---|---|
default | var(--color-primary) | General system updates, feature tips, neutral notifications |
success | var(--color-success) | Confirmed operations, completed exports, successful saves |
error | var(--color-danger) | Network errors, validation failures, failed operations |
warning | var(--color-warning) | Rate limit warnings, session expiration alerts, unsaved work |
// Variant examples
toast.show('Database backup created', { variant: 'success' });
toast.show('Network disconnected', { variant: 'error' });
toast.show('Storage limit at 92%', { variant: 'warning' });
toast.show('New comment received', { variant: 'default' });Manual Dismissal
toast.show() returns a unique string id. You can programmatically dismiss a toast before its duration expires:
const toastId = toast.show('Uploading file...', { duration: 15000 });
// Later when upload finishes:
toast.dismiss(toastId);
toast.show('Upload complete!', { variant: 'success' });Toast Options Reference
The show() function and programmatic helpers accept the following options:
| Option | Type | Default | Description |
|---|---|---|---|
variant | 'default' | 'success' | 'error' | 'warning' | 'default' | Semantic color variant of the notification |
description | React.ReactNode | undefined | Secondary supporting text below the main message |
duration | number | 4000 | Auto-dismiss time in milliseconds (set to Infinity to keep persistent) |
Accessibility & Animations
- Screen Readers: Container declares
aria-live="polite"and each individual notification appliesrole="status". - Keyboard Navigation: Includes an accessible close button with
aria-label="Close notification". - Hover to Pause: Hovering over an active toast pauses its auto-dismiss countdown timer so users have sufficient time to read long messages.
- Motion Safety: Automatically honors
prefers-reduced-motionmedia queries, replacing sliding transitions with instant opacity fades.
Best Practices
Do
- Mount
<ToastProvider>once at the application root layout. - Pair toasts with clear, actionable text.
- Use
descriptionfor helpful context (e.g. error reasons or next steps). - Rely on pause-on-hover for notifications with dense messages.
Don't
- Do not fire multiple identical toasts in rapid succession; consolidate notifications.
- Avoid using toasts for critical confirm/reject interactions; use
<DialogProvider>withnui.confirm()instead. - Do not hardcode fixed hex colors in toast bodies; let NUI semantic tokens adapt automatically across light and dark modes.
API Reference
Inherits all standard attributes and event handlers from { children: React.ReactNode } — Mount once at app root to enable toast context (useToast) and imperative toast bridging (nui.toast). Supports className for semantic NUICSS superclasses and ref forwarding.