News

Sonner React Toasts: Setup, Hooks & Advanced Customization





Sonner React Toasts: Setup, Hooks & Advanced Customization



Sonner React Toasts: Setup, Hooks & Advanced Customization

Short summary: Practical, production-ready guide to using Sonner as your React toast notifications library — from installation and hooks to promise-based toasts, customization, and accessibility best practices.

Why Sonner for React toast notifications?

Sonner is a lightweight React notification library designed for modern apps where toast messages must be predictable, composable, and easy to style. Unlike older monolithic alert systems, Sonner exposes concise hooks and a simple Toaster root that makes it straightforward to trigger toast messages from anywhere in your component tree.

From a developer perspective, Sonner emphasizes an imperative API that plays nicely with React hooks, minimizing rerenders and avoiding global event buses. That makes it a strong candidate for apps that require both programmatic toasts and declarative customization — for example, to show a “Saved” success toast after async form submissions or a persistent alert for offline status.

Operationally, Sonner supports promise-based toasts, multiple positions, and theme-friendly styling without forcing heavy CSS frameworks. This combination — small bundle, easy hooks, and flexible customization — explains why Sonner has become a go-to React toast library.

Installing and setting up Sonner in a React app

Start by installing Sonner from npm: npm install sonner or yarn add sonner. Then render the Toaster component near the root of your application (usually in App.jsx or index.jsx). The Toaster provides the runtime context that hook-based APIs use to enqueue notifications.

Example minimal setup (JSX):

import { Toaster } from 'sonner';

function App(){
  return (
    <>
      <Toaster />
      {/* rest of your app */}
    </>
  );
}

Once Toaster is mounted, use the exported hooks or helper functions to display toasts from anywhere. For complete step-by-step instructions and an annotated example, see this sonner tutorial: sonner tutorial. For package info and installation commands, see the package page: sonner installation.

Core concepts and React toast hooks

Sonner typically provides two interaction patterns: direct toast functions (e.g., toast.success, toast.error) and hook-based accessors (e.g., useToast or useToaster). The direct functions are convenient for quick notifications; hooks let you integrate toast actions inside components with local context or custom logic.

The hook-based pattern is especially useful for React’s functional components because it avoids importing global objects and supports encapsulation. A common pattern is to call a hook in a component that manages async work, then call the toast API on success or failure — keeping notification logic next to the business logic that triggers it.

Sonner’s APIs also emphasize toast IDs and update semantics: create a toast and keep its ID, then update or replace that toast rather than creating multiple notifications for a single process. This is essential for promise-toasts (loading → success → error) and reduces UI noise in heavy-interaction flows.

Customization, theming, and promise toasts

Styling Sonner is intentionally flexible. You can supply class names, style objects, or theme props depending on the library version. The typical strategy is to supply a small set of CSS variables or Tailwind-compatible classes to the Toaster so all toasts inherit consistent spacing and typography.

Promise-based toasts are a killer feature: they let you show a single toast that transitions through states. Pattern: display a pending toast when the operation starts, then update it to a success or error state when the promise resolves or rejects. This avoids multiple notifications for a single user action and communicates state transitions cleanly.

Example pseudo-code for a promise toast:

const promise = fetch('/api/save', {...});
toast.promise(promise, {
  loading: 'Saving…',
  success: 'Saved!',
  error: 'Save failed'
});

This pattern integrates with optimistic UI or long-running uploads. Sonner handles the UI update lifecycle so you can focus on logic and messaging.

Best practices: accessibility, positioning, and performance

Accessibility matters. Ensure toasts have proper ARIA roles and are announced to screen readers. Sonner includes accessible defaults, but you should validate with a screen reader and ensure toasts aren’t the only way critical information is conveyed to users with assistive tech.

Choose unobtrusive positions for toasts (top-right or bottom-right for non-critical info; top-center for global alerts). Avoid blocking important controls with persistent toasts. For mobile, prefer shorter durations and dismiss controls to avoid covering content.

  • Keep messages brief and actionable. Prefer a concise summary + optional CTA.
  • Use IDs to update existing toasts (avoid flooding).
  • Test performance with many concurrent toasts — limit queue size or auto-dismiss to maintain responsiveness.

Following these rules helps maintain a calm, performant notification system that respects users, accessibility, and the app’s visual hierarchy.

Advanced integration patterns

Integrate Sonner with global state or side-effect managers like React Query or Redux by centralizing toast triggers in your side-effect callbacks. For example, in a React Query onSuccess/onError you can trigger a toast that summarizes the result without duplicating code across components.

Another pattern is to build a small notification service wrapper around Sonner. Encapsulate message templates, severity mapping, and i18n keys so components call high-level helpers (notifySuccess(‘userSaved’)) instead of composing raw strings. This reduces duplication and keeps messaging consistent.

Finally, consider server-driven notifications: when the server triggers client-side notifications (websockets or SSE), translate events into toast messages but throttle or group them to avoid flooding users — Sonner’s queueing and update semantics make grouping straightforward.

Related user questions (People Also Ask & forums)

Below are common queries developers search for when evaluating or using Sonner and React toast libraries. They served as the input for the FAQ selection:

  1. How do I install and set up Sonner in React?
  2. How to create promise-based toasts (loading → success/error)?
  3. How to customize toast styles and animations?
  4. Does Sonner support multiple positions and stacking?
  5. Is Sonner accessible / ARIA compatible?
  6. How to dismiss or programmatically update a toast?
  7. How does Sonner compare to other React toast libraries (react-toastify, notistack)?
  8. Can Sonner work with SSR (Next.js)?

From these, the three most actionable questions are answered in the FAQ below to help you ship faster.

FAQ

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

Install via npm/yarn (npm i sonner), render <Toaster/> near your app root, then call the provided toast API or hooks to trigger notifications. For a step-by-step example and annotated explanation, consult this sonner tutorial.

How can I show a promise-based toast (loading → success/error)?

Use Sonner’s promise helper or manual pattern: show a pending toast when the operation starts, keep its ID, and update that same toast on resolution or rejection. Sonner’s built-in helpers (e.g., toast.promise) handle this lifecycle so users see one transitioning notification instead of multiple messages.

What accessibility practices are recommended for React toast messages?

Use ARIA roles, ensure toasts are announced by screen readers, provide keyboard focus or dismiss buttons when necessary, and test with assistive tech. Keep messages concise and avoid relying solely on toasts for critical workflows — pair them with persistent UI elements when needed.

Semantic Core (Primary & Secondary Keyword Clusters)

Primary queries

  • sonner
  • React toast notifications
  • sonner tutorial
  • React notification library
  • sonner installation

Secondary / intent-based queries

  • React toast messages
  • sonner setup
  • React toast hooks
  • sonner customization
  • React notification system
  • sonner promise
  • React toast library

Clarifying / LSI phrases & synonyms

  • toast notifications React
  • notification hooks for React
  • promise toast pattern
  • toast theming and styling
  • accessible alerts React
  • Toaster component
  • toast queue and update

Use these grouped keywords to shape headings, alt text, and anchor text naturally within your React docs and code examples.

Backlinks & Resources

Recommended references and authoritative links (useful to include in docs or README):

Need a compact example for copy-paste? Here’s a minimal pattern to include in a component that shows a promise toast:

import { toast, Toaster } from 'sonner';

function SaveButton(){ 
  const handleSave = async () => {
    const promise = api.saveData();
    toast.promise(promise, {
      loading: 'Saving…',
      success: 'Saved successfully',
      error: 'Failed to save'
    });
  };

  return <>
    <Toaster />
    <button onClick={handleSave}>Save</button>
  </>
}

Published with practical guidance for developers building reliable React notification systems. Happy toasts! 🎉