How Your Toast Library Works in React and Next.js
Toast notifications are the small, transient messages that appear in the corner of your screen to confirm an action, show an error, or deliver a quick update. In React and Next.js, a toast library like react-hot-toast or sonner handles the entire lifecycle—creating, displaying, stacking, and dismissing these messages—so you don’t have to build the UI and state management from scratch. This guide explains the core mechanics of how these libraries work, and how to integrate them into your own React or Next.js project.
What You'll Need
- A React project (Create React App, Vite, or similar) or a Next.js project (App Router or Pages Router)
- Node.js and npm (or yarn/pnpm) installed
- Basic familiarity with React components, hooks, and JSX
- For Next.js, a basic understanding of client vs. server components (since toasts run on the client)
Step-by-Step
- Choose a toast library. Popular options include
react-hot-toast(minimal, customizable),sonner(modern, built for React), andreact-toastify(feature-rich). For this guide, we'll usereact-hot-toastas the example—it’s widely used and has a simple API. - Install the library. Run
npm install react-hot-toast(oryarn add react-hot-toast) in your project root. This adds the package and its dependencies to yourpackage.json. - Add the Toaster component to your app. The library provides a
Toastercomponent that renders the container for all toasts. Place it once, typically in your root layout or a top-level component. In Next.js App Router, add it toapp/layout.tsx(orapp/layout.js) inside thebodytag. In a plain React app, add it to your mainAppcomponent. - Mark the component as client-side (Next.js only). Since the
Toasteruses browser APIs and state, it must be a Client Component. In Next.js App Router, add'use client'at the top of the file where you importToaster(or create a separate client component that wraps it). - Import the toast function. In any component where you want to trigger a notification, import the
toastfunction:import toast from 'react-hot-toast';. This function is the main API—it creates a new toast when called. - Call the toast function. Use toast.success('Saved!') , toast.error('Failed!') , or toast('Just a message') inside event handlers, effects, or async functions. For example, in a form submit handler: .
- Customize appearance (optional). You can pass options to
toast()or to theToastercomponent to change position, duration, styling, and icons. For instance,toast('Hello', { duration: 5000, icon: '👋' })or. - Handle async toasts (optional). Use
toast.promise(promise, { loading: 'Saving...', success: 'Saved!', error: 'Failed' })to automatically show loading, success, or error states based on a Promise's resolution. - Dismiss manually (optional). You can dismiss a specific toast by storing its ID:
const toastId = toast('Hello'); toast.dismiss(toastId);or dismiss all withtoast.dismiss().
Common Mistakes
- Forgetting to render the
Toastercomponent. If you calltoast()but theToasterisn't mounted, nothing appears. Always include it in your root layout. - Using the library in a Server Component (Next.js). Toast libraries rely on client-side state and effects. Importing them in a Server Component will cause errors. Always add
'use client'to the file that uses them. - Multiple
Toasterinstances. Rendering more than oneToastercan cause duplicate or overlapping toasts. Stick to a single instance. - Calling
toast()during render. Toast functions should be called in response to events (like clicks) or inuseEffect, not directly in the render body. Calling during render can cause infinite loops or unexpected behavior. - Ignoring z-index conflicts. Toasts appear above most content, but if you have modals or overlays with a higher z-index, they might cover the toasts. Adjust the
zIndexprop onToasterif needed.
Tips
- Use consistent positions. Choose one position (e.g., top-right) and stick to it across your app for a cohesive user experience.
- Set a reasonable duration. The default is 4000ms. For important errors, you might want a longer duration or no auto-dismiss (set
duration: Infinity). - Leverage toast.promise for async operations. It reduces boilerplate and gives users clear feedback during loading states.
- Style to match your design. Most libraries allow custom CSS or className props. Use your app's theme colors for a seamless look.
- Test on mobile. Ensure toasts are readable and don't block important UI on small screens. You can adjust the width or position.
Troubleshooting
- Toasts don't appear. Check that the
Toastercomponent is rendered and that you're callingtoast()after the component mounts. Also, verify there are no JavaScript errors in the console. - Toasts appear but disappear instantly. Ensure you're not accidentally calling
toast.dismiss()immediately. Also, check if a parent component is re-rendering and unmounting theToaster—move it to a stable location like the root layout. - Next.js: