React Hot Toast: Effortless Notifications

10/04/2020

Rating: 4.78 (11567 votes)

In the realm of modern web development, user feedback is paramount. Providing clear, concise, and timely notifications can significantly enhance the user experience, guiding them through interactions and confirming actions. For React developers, react-hot-toast emerges as a powerful and elegant solution for implementing these crucial visual cues. This lightweight, highly customisable library, crafted by Timo Lins, simplifies the process of displaying smoking hot notifications, making your application more engaging and user-friendly.

How do I trigger a 'react-hot-toast' notification?
To trigger a 'react-hot-toast' notification, first add it to your app and it will handle rendering all notifications. You can now trigger 'react-hot-toast' with 'Here is your toast'. Lightweight, customizable and beautiful by default. 'react-hot-toast' Smoking hot React Notifications.
Table

What is react-hot-toast?

react-hot-toast is a popular and exceptionally versatile library designed specifically for React applications. It excels at delivering simple, yet impactful, notification messages that appear momentarily on the screen, often referred to as 'toasts'. Its core philosophy revolves around ease of use, customisation, and a minimal footprint, ensuring it integrates seamlessly into any project without introducing unnecessary bloat.

Key Features of react-hot-toast

The appeal of react-hot-toast lies in its robust feature set, designed to cater to a wide range of notification needs:

  • Hot by Default: Notifications are displayed promptly and with a pleasing visual flair right out of the box.
  • Easily Customizable: Tailor the appearance and behaviour of your toasts to perfectly match your application's design language. This includes colours, positioning, duration, and more.
  • Promise API: Effortlessly handle asynchronous operations. react-hot-toast can automatically display a loading state while a promise is pending and update or dismiss the toast upon resolution or rejection. This is a game-changer for providing feedback on API calls or other background tasks.
  • Lightweight: With a bundle size of less than 5kb, including styles, it's an ideal choice for performance-conscious projects.
  • Accessible: Built with accessibility in mind, ensuring your notifications are perceivable by all users.
  • Headless Hooks: For ultimate control, the library provides headless hooks like useToaster(), allowing you to build your own custom toaster components and notification logic.

Installation

Getting react-hot-toast up and running in your project is straightforward. You can install it using your preferred package manager:

Using npm:

npm install react-hot-toast

Using pnpm:

pnpm add react-hot-toast

Getting Started: Triggering Your First Toast

Once installed, integrating react-hot-toast into your React application is remarkably simple. The primary steps involve adding the Toaster component and then using the toast function to emit notifications.

Step 1: Add the Toaster Component

The Toaster component is responsible for rendering all the notifications that are triggered throughout your application. It's essential to place this component at a high level in your component tree, typically within your main App component, to ensure it can catch all toast events.

import React from 'react'; import toast, { Toaster } from 'react-hot-toast'; function App() { return ( 
{/* Your other application components */}
); } export default App;

Step 2: Triggering a Basic Toast

With the Toaster in place, you can now trigger notifications from anywhere in your application using the imported toast function. This function takes the message content as its first argument.

import React from 'react'; import toast, { Toaster } from 'react-hot-toast'; const notify = () => { toast('Here is your toast.'); }; function App() { return ( 
); } export default App;

In this example, clicking the button labelled "Make me a toast" will trigger the notify function, which in turn calls toast('Here is your toast.'). This will render a default toast notification with the specified message.

Customising Your Toasts

While the default toasts are visually appealing, react-hot-toast offers extensive customisation options to align with your brand and user experience goals. You can pass an options object as the second argument to the toast function.

Common Customisation Options:

  • duration: Control how long the toast remains visible (in milliseconds).
  • position: Define where the toast appears on the screen (e.g., 'top-center', 'bottom-right', 'top-left').
  • className: Apply custom CSS classes for complete styling control.
  • style: Directly apply inline styles.
  • icon: Replace the default icon with your own custom SVG or component.

Example of Customisation:

const customNotify = () => { toast.success('Profile updated successfully!', { duration: 5000, // 5 seconds position: 'top-center', style: { background: '#363636', color: '#fff', }, icon: '✅', }); }; 

Using the Promise API

The Promise API is where react-hot-toast truly shines for handling asynchronous operations. It simplifies providing visual feedback during loading states.

const handleSave = async () => { toast.promise( new Promise(resolve => setTimeout(resolve, 2000)), // Simulate an API call { loading: 'Saving...', success: Settings saved!, error: Could not save., }, { duration: 4000, position: 'bottom-right', } ); }; 

In this example, when handleSave is called, a toast will initially display 'Saving...'. Once the promise resolves, it will be replaced with 'Settings saved!'. If the promise rejects, it will show 'Could not save.'.

Advanced Usage: Custom Toasts

For even greater flexibility, you can create fully custom toast components.

const MyCustomToast = ({ message }) => ( 
{message}
); const notifyCustom = () => { toast.custom(); };

Headless Hooks for Maximum Control

The useToaster() hook provides access to the underlying toaster logic, allowing you to build your own UI for managing and displaying toasts. This is for developers who need fine-grained control over the entire notification system.

Best Practices

  • Keep messages concise: Toasts are for brief updates. Avoid lengthy text.
  • Use appropriate types: Leverage toast.success, toast.error, and toast.warning for semantic clarity.
  • Consider placement: Choose a toast position that doesn't obstruct critical UI elements.
  • Manage duration wisely: Ensure users have enough time to read the message without it lingering too long.
  • Provide clear feedback: Use toasts to confirm user actions or inform them of important status changes.

Frequently Asked Questions (FAQ)

Q: Can I have multiple toasts visible at once?
A: Yes, by default, react-hot-toast allows multiple toasts to be visible. You can control this behaviour through the Toaster component's props.
Q: How do I dismiss a toast programmatically?
A: You can dismiss a toast by calling the toast.dismiss(id) function, where id is the unique identifier returned when the toast was created.
Q: Is react-hot-toast compatible with server-side rendering (SSR)?
A: Yes, react-hot-toast is designed to be SSR-friendly. The Toaster component will only render on the client side.
Q: Can I animate the toasts?
A: Yes, you can leverage CSS transitions and animations by using the className or style props to achieve custom animations.

Conclusion

react-hot-toast offers a delightful and efficient way to incorporate notifications into your React applications. Its blend of simplicity, customisation, and powerful features like the Promise API makes it an invaluable tool for enhancing user feedback and improving the overall user experience. By following these guidelines, you can effectively trigger and manage stunning, informative toasts that elevate your React projects.

If you want to read more articles similar to React Hot Toast: Effortless Notifications, you can visit the Automotive category.

Go up