How would you design a notification/toast system in React?
Build a global toast/notification system with portal rendering, queueing, auto-dismiss, animations, and accessibility.
Advertisement
đź§© Scenario
You need a global toast/notification system usable from anywhere in the app:
- Show success, error, warning, or info toasts
- Support auto-dismiss + manual close
- Allow multiple toasts with queueing
- Animations (enter/exit)
- Accessible via screen readers
- Should work even if triggered deep inside component tree
đź§ Answer (Design Overview)
Core Design Principles
-
Global State + Context Provider: Expose a
useToast()hook that any component can call. -
Portal Rendering: Render toasts at the document root using
ReactDOM.createPortal(). -
Toast Store: Maintain:
{ id, message, type, duration, createdAt }. -
Queue + Auto-Dismiss: Each toast removes itself after
durationms. -
Animations: Apply CSS transitions for slide-in/slide-out.
-
Accessibility: Use
role="alert"for important messages.
Tradeoffs:
- Context-based systems are simple but need caution with re-renders.
- External event emitter avoids rerenders but adds complexity.
🎮 Live Demo: Notification Toast System
🔍 Real-World Tips
- Use Framer Motion for smoother animations.
- Add stacking logic to push older toasts downward.
- Add swipe-to-dismiss on mobile.
- Add global maxToasts or queueing rules.
- Provide
Promise-basedAPI:showAsync("Uploading...").
đź§ Diagram
flowchart TD A[Trigger Toast] --> B[Context.show] B --> C[Push to Toast State] C --> D[Portal Renderer] D --> E[Animated Toast] E -->|Auto dismiss| F[Remove Toast]
Quick Practice
- Add a close button in each toast.
- Add
maxToasts: 3and queue additional ones. - Animate exit using opacity fade-out.
- Add support for toast actions (e.g., "Undo").
Summary
- Use context + portal for global toast rendering.
- Auto-dismiss + animations create a polished UX.
- Keep toast data simple:
{id, message, type, duration}. - Add queueing, actions, and accessibility for production-grade systems.
Why render toasts in a portal?
To keep them above other UI layers regardless of component nesting.
How do you prevent overlapping toasts?
Use a queue or stack, and apply staggered offsets with transitions.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement