This code implements a robust and customizable notification system in React. It addresses the common need for providing users with feedback on actions, errors, or informational updates. The system uses React's Context API for global state management, making notifications easily accessible throughout the application.
How it Works:
- Context API: A
NotificationContext is created to manage the state of all notifications. The useNotifications hook provides a simple way to access and manipulate this context.
- NotificationProvider: This component wraps the application and provides the notification context to its children. It manages an array of notifications using the
useState hook.
- addNotification: This function adds new notifications to the array. It generates a unique ID for each notification, adds a timestamp, and optionally sets a timeout for auto-dismissal based on a provided
duration property.
- removeNotification: This function removes a notification from the array based on its ID.
- removeAllNotifications: This function clears all notifications from the array.
- Notification Component: This reusable component renders individual notifications. It displays the notification's type (success, error, warning, info), title, message, optional actions, and a progress bar if a duration is specified. It also handles smooth slide-out animations upon dismissal.
- NotificationContainer: This component renders all active notifications in a visually appealing container positioned at the top right corner of the screen.
- Demo Component: This showcases how to use the notification system with various notification types (success, error, warning, info), including persistent notifications and notifications with custom actions.
Key Libraries/Concepts:
- React Context API
- useState, useEffect, useCallback hooks
- Functional components
- Custom hooks
Use Cases:
- Displaying success messages after form submissions.
- Showing error messages during API calls.
- Providing warnings about potential issues.
- Displaying informational messages to guide users.
- Implementing persistent notifications for critical alerts.
Example Scenarios:
- An e-commerce application could use the system to confirm order placement, display errors during checkout, or warn about low stock levels.
- A social media platform might use it to notify users of new messages, friend requests, or activity on their posts.
- A task management tool could use it to indicate task completion, alert about deadlines, or report errors during synchronization.
This system allows for easy integration and customization to fit various application needs.