Managing Toast State and Queue
You'll learn how to organize and control multiple toast notifications so they appear in the correct order, don't overwhelm users, and respect priority rules.
The Challenge
When multiple notifications fire at once (form saved, email sent, error occurred), showing them all immediately creates chaos. You need a toast manager — think of it as an airport control tower that decides which planes (toasts) land on the runway (screen) and in what order.
Core Concepts
The Toast Queue
Maintain an array of pending toasts in your state. When a new toast arrives, add it to the queue rather than displaying it immediately:
const [toasts, setToasts] = useState([]);
const [maxVisible, setMaxVisible] = useState(3);
Adding to the Queue
When creating a toast, assign it a unique ID and optional priority:
function addToast(message, type, priority = 0) {
const newToast = {
id: Date.now(),
message,
type,
priority,
timestamp: Date.now()
};
setToasts(prev => [...prev, newToast]);
}
Priority Ordering
Sort toasts so errors appear before info messages:
const sortedToasts = toasts.sort((a, b) => b.priority - a.priority);
Limiting Visible Toasts
Only display the first maxVisible toasts, keeping others queued:
const visibleToasts = sortedToasts.slice(0, maxVisible);
Removing Toasts
When a toast dismisses (auto or manual), remove it from state so the next queued toast appears:
function removeToast(id) {
setToasts(prev => prev.filter(toast => toast.id !== id));
}
The Pattern in Practice
Your toast manager becomes a centralized system: add toasts from anywhere in your app, and the manager handles display limits, priority sorting, and sequential presentation as space becomes available.
Key Takeaway: A toast queue with priority ordering and visibility limits prevents notification overload while ensuring critical messages reach users first.