Overview
TheToastContext provides a centralized notification system for displaying toast messages to users. It supports multiple toast types (success, error, warning, info) with automatic dismissal and queue management.
Components
ToastProvider
The context provider component that manages toast state and provides notification functions.The child components that will have access to the toast context
Example: App Setup
Hook API
useToast
A custom hook that provides access to toast notification functions. Must be used within aToastProvider.
Returns: Toast context object with the following properties:
Array of currently active toast objects. Each toast has
id, message, type, and duration propertiesGeneral function to add a toast notificationParameters:
message(string, required): The toast message to displaytype(string, optional): Toast type - ‘success’, ‘error’, ‘warning’, or ‘info’. Defaults to ‘info’duration(number, optional): How long to show the toast in milliseconds. Defaults to 3000. Set to 0 for persistent toast
Manually remove a toast by its ID
Convenience method to show a success toast. Uses green styling with check icon
Convenience method to show an error toast. Uses red styling with error icon
Convenience method to show an info toast. Uses blue styling with info icon
Convenience method to show a warning toast. Uses yellow styling with warning icon
Usage Examples
Success Toast
Error Toast
Custom Duration
Persistent Toast
All Toast Types
Real-World Example: Form Submission
Toast Object Structure
Each toast in thetoasts array has the following structure:
Displaying Toasts
To actually render toasts on screen, use theToastContainer component:
ToastContainer component:
- Reads toasts from the context using
useToast() - Positions toasts in the bottom-right corner
- Handles animations (slide in/out)
- Shows a progress bar for auto-dismissing toasts
- Pauses auto-dismiss on hover
- Provides close buttons for manual dismissal
Features
Automatic Queue Management
Toasts are automatically added to a queue and displayed in order. Multiple toasts stack vertically.Auto-Dismiss
By default, toasts auto-dismiss after 3 seconds. You can:- Customize the duration per toast
- Set duration to 0 for persistent toasts
- Manually dismiss using
removeToast(id)
Type-Based Styling
Each toast type has distinct styling:- Success: Green background with check icon
- Error: Red background with error icon
- Warning: Yellow background with warning icon
- Info: Blue background with info icon
Error Handling
The hook throws an error if used outside of aToastProvider:
Implementation Details
The context uses React hooks internally:useStatefor managing the toasts arrayuseCallbackfor memoized toast functions- Unique IDs generated using
Date.now() - Auto-removal via
setTimeoutfor time-based dismissal
Related
- SettingsContext - Often used together for settings changes
- ToastContainer Component - Required for rendering toasts
