Sonner: React Toast Notifications — Tutorial, Setup & Examples





Sonner: React Toast Notifications — Tutorial, Setup & Examples

A concise, practical guide to using sonner — the modern, lightweight React toast library. Installation, Promise API, customization, hooks, accessibility and production tips.

Quick analysis of the SERP and user intent

Based on prominent English-language results for the supplied keywords (sonner, React toast notifications, sonner tutorial, sonner installation, sonner example, etc.), search intent splits roughly like this:

– Informational: "sonner tutorial", "sonner example", "React toast messages" — users want how-to guides and code samples.
– Transactional/Commercial: "sonner installation", "React toast library", "React notification library" — users often evaluate and install packages.
– Mixed (how-to + evaluation): "sonner customization", "React toast hooks", "sonner promise" — queries expecting implementation patterns and best practices.

Top results typically include: official README/examples, short tutorials (blog posts, dev.to), CodeSandbox demos, and comparative lists of React toast libraries. The common structure across competitors: brief intro, quick install, minimal example, and a short section on customization or Promise-based notifications. Good articles add accessibility and API notes; great ones add patterns and production considerations.

Semantic core (expanded keywords and clusters)

Below is the SEO semantic core derived from your seed keywords, grouped by intent and purpose. These are ready to use organically in headings and body text.

{
  "primary": {
    "sonner": "high",
    "sonner tutorial": "medium",
    "sonner installation": "medium",
    "sonner example": "medium",
    "sonner setup": "medium",
    "sonner promise": "medium",
    "sonner customization": "medium"
  },
  "secondary": {
    "React toast notifications": "high",
    "React toast messages": "medium",
    "React notification library": "high",
    "React alert notifications": "low",
    "React toast hooks": "medium",
    "React notification system": "low",
    "React toast library": "high"
  },
  "LSI_and_related": [
    "toast library for React",
    "notification hooks",
    "toast promise API",
    "toast customization",
    "dismissable toasts",
    "toast stacking",
    "toast positions (top-right, bottom-left)",
    "accessible toasts (aria-live)",
    "toast animations",
    "snackbars vs toasts",
    "toast duration settings",
    "rich colors sonner"
  ],
  "clusters": {
    "installation_setup": ["sonner installation","sonner setup","React toast library","React notification library"],
    "basic_usage": ["sonner example","React toast messages","sonner","React toast notifications"],
    "advanced": ["sonner promise","React toast hooks","sonner customization","React notification system"],
    "accessibility_best_practices": ["accessible toasts","aria-live","dismissable toasts"]
  }
}
  

Use these phrases naturally across the article, in H2/H3s and in image alt text. Avoid keyword stuffing — the list is here to help you vary language and satisfy different query intents.

Top user questions (People Also Ask / forums)

Collected likely popular questions related to Sonner and toast notifications:

  • How do I install and set up Sonner in React?
  • How does Sonner's promise API work?
  • Can I customize Sonner toasts (styles, position, duration)?
  • Does Sonner support rendering custom JSX inside toasts?
  • How to integrate toasts with React hooks or global state?
  • Are Sonner toasts accessible (screen reader friendly)?
  • How to dismiss or queue multiple toasts?
  • Performance impact of using toasts in a large app?

Chosen for final FAQ (top 3):

  1. How do I install and set up Sonner in a React project?
  2. Can Sonner handle promise-based toasts (loading → success/error)?
  3. How do I customize the appearance and behavior of Sonner toasts?

Installation, setup and a runnable example

Start with installation — the part everyone skims and later regrets not reading. In a terminal run:

npm install sonner
# or
yarn add sonner

Then add a global <Toaster /> near your app root (e.g., inside App.tsx or at the layout level). The Toaster is the container that renders toasts; the API is intentionally imperative so you can trigger toasts from anywhere.

import React from 'react';
import { Toaster, toast } from 'sonner';

export default function App(){
  return (
    <>
      <Toaster />
      <main>
        <button onClick={() => toast.success('Saved!')}>Save</button>
      </main>
    </>
  );
}

That example covers the essentials: install, import, mount Toaster and call toast.success / toast.error / toast(). It's concise and effective — the whole point of a good toast library.

Promise-based toasts and integration patterns

One of Sonner's practical features is handling promises: show a "loading" toast while an async operation runs, then update it to success or error automatically. This pattern prevents duplicate toasts and provides consistent UX for network actions.

const save = async () => {
  const promise = fetch('/api/save', { method: 'POST' });
  toast.promise(promise, {
    loading: 'Saving…',
    success: 'Saved successfully 🎉',
    error: 'Save failed. Try again.'
  });

  await promise;
};

Use this for fetches, file uploads, or any promise-returning API. It keeps UI logic centralized and readable. For more advanced control (e.g., updating the same toast with progress), wrap the promise and call toast() manually with an id you manage.

If you want a React hook pattern, don't panic: Sonner uses an imperative API, but you can wrap it in a tiny hook that exposes semantic methods (success, error, promise) from context — making tests easier and the API consistent across your app.

import { toast } from 'sonner';
export function useToast() {
  return {
    success: (msg) => toast.success(msg),
    error: (msg) => toast.error(msg),
    promise: (p, msgs) => toast.promise(p, msgs)
  };
}

Customization, styling and accessibility

Sonner keeps customization simple: position, duration, and color variants are typically provided as Toaster props. For real styling control, render custom JSX in toasts or wrap toast calls in helpers that add consistent markup and ARIA attributes.

Common customization options you will want to expose:

  • Position (top-right, bottom-left, etc.) and stacking behavior
  • Duration (how long to auto-dismiss)
  • Color schemes and action buttons inside toasts

Accessibility checklist (don't skip this): use aria-live for the container, ensure toasts are keyboard-focusable when they contain actions, and provide dismiss controls. Sonner's default behavior covers many cases, but verify with a screen reader and keyboard-only navigation.

Example: custom toast with an action button

toast((t) => (
  <div>
    <strong>Delete failed</strong>
    <button onClick={() => retry() }>Retry</button>
  </div>
));

That pattern lets you inject fully controlled JSX into the toast; keep content concise and accessible.

Best practices, performance & production tips

Use toasts for lightweight, transient feedback (saved, sent, error). Avoid dumping verbose error stacks or long paragraphs into toasts. They should inform, not document.

To reduce noise and avoid spamming users: debounce repeated toasts, group similar messages, and use the promise API to update a single toast instead of creating many. For global errors, prefer a small banner or modal when recovery requires user action.

Performance: toasts are cheap. The Toaster mounts once and updates its internal state; the main risk is rendering complex custom JSX for each toast. Keep components lean, and avoid heavy synchronous computations in toast render paths.

Minimal production-ready checklist

  • Mount a single <Toaster /> at app root. (Avoid multiple containers.)
  • Wrap toast calls with a small utility hook or module for consistency and easier testing.
  • Use toast.promise for async workflows. Debounce or dedupe repetitive messages.
  • Verify accessibility: aria-live, keyboard focus for interactive toasts and announce changes to screen readers.

FAQ — three concise answers

How do I install and set up Sonner in a React project?

Install with npm i sonner (or yarn). Import {`{ Toaster, toast }`} from 'sonner', put <Toaster /> in your app root, and use toast.success('…'), toast.error('…') or toast() to show messages.

Can Sonner handle promise-based toasts (loading → success/error)?

Yes—use toast.promise(promise, { loading, success, error }). The library shows a pending toast while the promise resolves and updates it automatically on success or failure.

How do I customize the appearance and behavior of Sonner toasts?

Configure Toaster props (position, duration) and render custom JSX inside toasts when needed. Wrap behavior in a small helper/hook for consistent styling. Always check accessibility (aria-live, dismiss buttons) after customization.

Semantic core (copy for your CMS)

Primary keywords:
- sonner
- sonner tutorial
- sonner installation
- sonner example
- sonner setup
- sonner promise
- sonner customization

Secondary keywords and LSI:
- React toast notifications
- React toast messages
- React notification library
- React alert notifications
- React toast hooks
- React notification system
- React toast library
- toast library for React
- notification hooks
- toast promise API
- toast customization
- dismissable toasts
- toast stacking
- toast positions
- accessible toasts
- toast animations
- snackbars vs toasts

Clusters:
- installation_setup: sonner installation, sonner setup, React toast library
- basic_usage: sonner example, React toast messages, sonner
- advanced: sonner promise, React toast hooks, sonner customization
- accessibility_best_practices: accessible toasts, aria-live, dismissable toasts
  


תפריט
נגישות