Chef flipping glowing toast in a UI-themed kitchen with a British shorthair cat watching

Sizzle Up Your React App with React Hot Toast

The Gray Cat
The Gray Cat

React Hot Toast is a lightweight and customizable notification library that adds a dash of flavor to your React applications. With its easy-to-use API and beautiful default styles, it’s the perfect ingredient to enhance your user interface and keep your users informed in style.

Spicing Up Your UI: Key Features of React Hot Toast

React Hot Toast comes packed with a variety of features that make it stand out:

  • Hot and Ready: Beautiful notifications right out of the box
  • Customization Galore: Easily tweak styles and behavior to match your app’s design
  • Promise-based API: Automatically show loading states for asynchronous operations
  • Featherweight Champion: Weighs in at less than 5kb, including styles
  • Accessibility Baked In: Ensures all users can interact with your notifications
  • Headless Mode: Create your own notification components with the useToaster() hook

Preparing the Kitchen: Installation

Let’s start by adding React Hot Toast to your project. You can use either npm or yarn:

Using npm

npm install react-hot-toast

Using yarn

yarn add react-hot-toast

The First Slice: Basic Usage

To get started with React Hot Toast, you’ll need to add the Toaster component to your app and use the toast function to create notifications.

Setting the Table

First, import the necessary components and add the Toaster to your main app component:

import toast, { Toaster } from 'react-hot-toast';

const App = () => {
  return (
    <div>
      {/* Your app content */}
      <Toaster />
    </div>
  );
};

The Toaster component is responsible for rendering all the notifications in your app. You only need to include it once, typically at the root level of your application.

Serving Your First Toast

Now that the table is set, let’s create a simple notification:

const notifyUser = () => toast('Welcome to React Hot Toast!');

const WelcomeComponent = () => {
  return (
    <button onClick={notifyUser}>
      Click me for a toast!
    </button>
  );
};

When the button is clicked, a notification will appear with the message “Welcome to React Hot Toast!“. It’s that simple!

Gourmet Toasts: Advanced Usage

React Hot Toast offers a variety of ways to customize and enhance your notifications. Let’s explore some of the more advanced features.

Flavored Toasts: Success, Error, and Loading

React Hot Toast provides pre-styled notifications for common use cases:

const handleFormSubmit = async () => {
  toast.loading('Submitting your data...');
  try {
    await submitForm();
    toast.success('Data submitted successfully!');
  } catch (error) {
    toast.error('Oops! Something went wrong.');
  }
};

These styled toasts come with appropriate icons and colors, making it easy to convey the status of operations to your users.

Custom Recipe: Tailoring Your Toasts

You can customize the appearance and behavior of your toasts using options:

toast('Your custom toast is ready!', {
  duration: 4000,
  position: 'top-center',
  icon: '🍞',
  style: {
    borderRadius: '10px',
    background: '#333',
    color: '#fff',
  },
});

This creates a toast with a custom duration, position, icon, and styling. The possibilities for customization are vast, allowing you to match your toasts perfectly to your app’s design.

Promise-based Toasts: A Full Course Meal

React Hot Toast shines when dealing with asynchronous operations. You can create a toast that automatically updates based on the promise state:

const fetchData = async () => {
  const promise = fetchDataFromAPI();

  toast.promise(promise, {
    loading: 'Fetching data...',
    success: (data) => `Successfully fetched ${data.length} items`,
    error: 'Could not fetch data',
  });

  return promise;
};

This code will show a loading toast while the data is being fetched, then automatically update to a success or error toast based on the promise result.

Dismissing Toasts: Clearing the Table

Sometimes you might want to programmatically dismiss toasts. React Hot Toast makes this easy:

const toastId = toast.loading('Processing...');

// Later in your code
toast.dismiss(toastId);

// Or dismiss all toasts at once
toast.dismiss();

This is particularly useful for long-running operations or when you need to update the UI based on certain conditions.

The Perfect Blend: Putting It All Together

Let’s create a more complex example that showcases multiple features of React Hot Toast:

import React, { useState } from 'react';
import toast, { Toaster } from 'react-hot-toast';

const AdvancedToastDemo = () => {
  const [isLoading, setIsLoading] = useState(false);

  const simulateAsyncOperation = () => new Promise((resolve) => setTimeout(resolve, 2000));

  const handleComplexOperation = async () => {
    setIsLoading(true);
    const toastId = toast.loading('Initiating complex operation...');

    try {
      await simulateAsyncOperation();
      toast.success('Operation completed successfully!', {
        id: toastId,
        icon: '🎉',
        duration: 5000,
        position: 'bottom-right',
      });
    } catch (error) {
      toast.error('Operation failed. Please try again.', { id: toastId });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <button onClick={handleComplexOperation} disabled={isLoading}>
        {isLoading ? 'Processing...' : 'Start Complex Operation'}
      </button>
      <Toaster />
    </div>
  );
};

export default AdvancedToastDemo;

This example demonstrates loading states, promise-based toasts, custom styling, and dynamic updates based on the operation’s outcome.

The Chef’s Special: Conclusion

React Hot Toast brings a delightful and user-friendly notification system to your React applications. Its simplicity in basic usage, combined with the depth of customization options, makes it a versatile tool for developers of all levels. Whether you’re building a small personal project or a large-scale application, React Hot Toast can help you keep your users informed and engaged with minimal effort and maximum style.

By incorporating React Hot Toast into your project, you’re not just adding notifications – you’re enhancing the overall user experience with smooth, attractive, and informative toasts that can be tailored to fit any design requirement. So go ahead, give your React app that extra sizzle with React Hot Toast!

Comments