Sonner for React: Fast Tutorial & Advanced Toast Notifications

  1. ראשי
  2. בלוג
  3. Sonner for React: Fast Tutorial & Advanced Toast Notifications





Sonner for React: Fast Tutorial & Advanced Toast Notifications





Sonner for React: Fast Tutorial & Advanced Toast Notifications

Quick answer: Sonner is a lightweight, accessible React toast notifications library that gives you simple APIs (including promise-based toasts and hooks) to show non-blocking alerts with minimal code.

Why choose sonner as your React notification library?

Notifications are a core UX element—users expect immediate feedback that an action succeeded, failed, or is in progress. Sonner focuses on low friction: tiny bundle size, sensible defaults, and built-in accessibility. It fits projects that value speed and predictable behavior without heavy configuration.

Sonner exposes a concise API (toast, Toaster, useToast) so you can show messages from UI handlers, async flows, or global services. That API design reduces boilerplate compared with larger libraries, meaning fewer places to test and maintain.

It also supports advanced patterns like promise toasts (loading → success/error) and hook-based orchestration—important for modern React apps using async operations. For an extended walkthrough see this sonner tutorial.

Installation and initial setup

Installing sonner is straightforward and fits any React or Next.js project. Pick your package manager and install the package into your app root.

npm install sonner
# or
yarn add sonner
# or
pnpm add sonner

Next, add the Toaster at your application’s top level (App.jsx, App.tsx, or _app.tsx for Next.js). The Toaster is a lightweight portal that mounts toast elements; you can set global options like default position or duration there.

Example root integration:

import { Toaster } from 'sonner'

export default function App({ Component, pageProps }) {
  return (
    <>
      
      
    
  )
}

Backlinks: For an in-depth sonner installation walkthrough and advanced examples, check the official docs at sonner.js.org or the community tutorial Advanced Toast Notifications with sonner.

Basic usage and realtime examples

Once Toaster is mounted, you can import and call toast from anywhere in your app. The API is synchronous and returns an ID for programmatic control. Basic usage covers success, error, and neutral messages.

Keep UI handlers thin. Let the toast handle user feedback while the logic lives in services or hooks. This separation makes testing and reuse easier—your button click handler only triggers the toast and delegates logic to the service layer.

import { toast } from 'sonner'

function handleSave() {
  // do work...
  toast.success('Saved successfully')
}

function handleError() {
  toast.error('Something went wrong')
}

The returned ID is useful when you need to update or dismiss a specific toast:

const id = toast('Uploading...')
/* later */
toast.dismiss(id)

Sonner also supports actions inside a toast (like “Undo”) and clickable content—use these sparingly to keep toasts non-blocking and fast to read.

Promise toasts and hook-based flows

A powerful piece of sonner is the promise API: pass a promise and sonner will show a loading toast, then automatically update it to success or error when the promise resolves or rejects. This pattern keeps your async UX consistent and reduces manual state management.

import { toast } from 'sonner'

async function handleUpload(file) {
  await toast.promise(
    uploadFile(file),
    {
      loading: 'Uploading...',
      success: 'Upload complete!',
      error: 'Upload failed'
    }
  )
}

This pattern is ideal for API calls, file uploads, or long-running tasks where you want a single ephemeral message that reflects the task state. The promise toast uses the same Toaster lifecycle and respects global options like duration.

If you use hooks, useToast gives instance-level control for more complex flows (namespacing, targeting, or multi-toaster setups). That lets you scope notifications to a modal or a specific UI region.

import { useToast } from 'sonner'

function MyComponent() {
  const { toast } = useToast()
  const id = toast('Working...')
  // update or dismiss later
}

Customization, theming, and accessibility

Sonner ships minimal styles, designed so you can theme via CSS, utility classes, or CSS-in-JS. Customize global appearance through Toaster props or create fully custom renders for each toast type when you need bespoke UI.

Accessibility is built-in: toasts use polite ARIA roles and focus management patterns suitable for screen readers. Still, validate your custom templates to ensure they expose meaningful text to assistive tech.

Example custom toast render to include an action button and an icon:

toast((t) => (
  <div role="status" aria-live="polite">
    <strong>{t.title || 'Notice'}</strong>
    <button onClick={() => doUndo(); toast.dismiss(t.id)}>Undo</button>
  </div>
))

Use duration, position, and closable options to tune behavior per toast. For critical alerts, increase duration and make them closable; for transient confirmations keep durations short.

Advanced patterns and production best practices

In production apps you’ll want to standardize notification messages in a service layer or use a central event bus. Avoid sprinkling raw strings across components—this improves localization and consistency.

Testing: mock the toast API in unit tests so UI tests focus on the action, not the notification rendering. For integration tests, assert that the appropriate toast function was called or that the Toaster DOM contains expected text.

Performance: sonner is lightweight but avoid queuing dozens of toasts. Coalesce repetitive notifications or use throttling/debouncing around frequent events (e.g., auto-save). If you must show many, consider batching into a single summary toast.

Pro tip: For voice interfaces and assistant queries, keep notification text short and declarative (subject + verb + result). This improves transcription and voice feedback clarity.

Common pitfalls and troubleshooting

Missing Toaster: the most common mistake is calling toast without mounting Toaster. Ensure the Toaster exists once in the root; for tests, mount a mock Toaster or stub the API.

Server-side rendering: put Toaster inside a client-only boundary. For Next.js, mount it in _app.tsx or within a useEffect to avoid SSR markup mismatches.

If styles look off, check for CSS reset or global rules conflicting with the toast container. Use scoped classes or CSS specificity to override only the parts you need.

Semantic core: expanded keyword clusters

This semantic core is designed to help search optimization and to guide content coverage. Use these grouped keywords naturally in headings, code comments, and descriptive text.

  • Primary (main target queries): sonner, React toast notifications, React notification library, React toast library, sonner tutorial, sonner installation
  • Secondary (related intent & features): React toast messages, React alert notifications, sonner setup, sonner example, React notification system, sonner customization, sonner promise
  • Clarifying (LSI, synonyms, long-tail): toast hooks, toast promise API, toast customization React, toast notifications accessibility, toast actions undo, toast dismissal programmatic, lightweight notification library

Popular user questions (collected)

These are common queries people ask when evaluating or using sonner and React toast libraries:

  1. How do I install sonner in a React project?
  2. What API does sonner expose for promise-based toasts?
  3. Can I customize the toast appearance and duration?
  4. How do I test components that call toast?
  5. Does sonner support accessibility (ARIA, screen readers)?
  6. How to configure multiple Toasters or scoped notifications?
  7. How to dismiss a toast programmatically?
  8. Will sonner work with server-side rendering (Next.js)?
  9. Are there built-in toast icons or should I add my own?

FAQ

How do I install sonner in a React project?

Install with npm, yarn, or pnpm and mount <Toaster /> at the app root. Then import toast or useToast and call the API from handlers. Example:

npm install sonner
import { Toaster, toast } from 'sonner'
/* In root */
<Toaster />
toast.success('Done')

Can sonner handle promise-based toasts (loading → success/fail)?

Yes. Use toast.promise(myPromise, { loading, success, error }). Sonner shows a loading toast and updates it automatically based on promise resolution. This is ideal for uploads and API calls because it keeps UI state concise and consistent.

How can I customize toast appearance and behavior with sonner?

Customize via Toaster props (position, duration), custom render functions per toast, or global CSS/utility classes. For complex UIs, render custom JSX inside the toast callback and manage actions or buttons there. Always validate ARIA roles if you replace built-in templates.

Links & Backlinks

Further reading and resources:

SEO Title: Sonner for React: Fast Tutorial & Advanced Toast Notifications

Meta Description: Learn sonner installation, setup, customization, and promise toasts in React. Practical examples, hooks, and best practices for a production-ready notification system.


תפריט
נגישות