Sonner for React — Advanced Toast Notifications & Setup


Sonner for React — Advanced Toast Notifications & Setup

Practical guide: install, hook usage, promise toasts, customization, and performance tips for production-ready notifications.

Overview: Why choose Sonner for React notifications?

Sonner is a modern, tiny, and flexible toast notification library built for React—focused on ergonomics, accessibility, and predictable behavior. Unlike older monolithic solutions, Sonner provides a small API surface: a provider, a hook, and a handful of utilities that cover most notification workflows without imposing a styling system.

For developers who want fast setup, sensible defaults, and first-class support for promise-based toasts (loading → success → error flows), Sonner hits the sweet spot. It also integrates cleanly with custom styling systems (CSS modules, Tailwind, styled-components) so you retain design control while benefiting from battle-tested UI patterns.

Use Sonner when you need: non-blocking alerts, ephemeral messages, promise lifecycle notifications, or toast stacks that respect ARIA and keyboard interactions. If your app needs full modal-like interactions or complex queuing, pair Sonner with a dedicated state manager or keep it for transient feedback only.

Installation & Setup (fast path)

Install Sonner via npm or yarn. This single dependency plus a provider in your app root is all you need to start showing toasts. Example: npm i sonner or yarn add sonner followed by wrapping your app with <ToasterProvider />. For a thorough step-by-step, see this sonner installation and tutorial: Sonner tutorial & advanced examples.

Minimal setup is intentional: Provider for global config and a single hook (or direct API) to create toasts. This keeps render trees small and ensures performance is predictable across routes. You can opt into global placement, default durations, and animation presets at the provider level.

Need a quick checklist? Make sure your root layout includes the provider and that your bundler handles CSS (if you add custom styles). If you prefer not to import global CSS, use inline styling or your own component wrappers around Sonner’s render functions.

Core Concepts & Hooks

Sonner exposes a compact set of primitives: a Toaster provider, a useToaster hook (or an imperative API), and utility functions to create success/error/loading (promise) toasts. The hook returns methods to push and dismiss toasts and to inspect the currently rendered stack if needed.

Typical flow: call toast(‘Message’) for simple alerts, toast.success(‘Saved’) for quick statuses, and toast.promise(promise, { loading, success, error }) for asynchronous feedback. The promise helper transitions the toast state automatically, reducing boilerplate for common patterns like saving or fetching data.

Hooks integrate with component lifecycle: they return stable functions so you can call them from event handlers, effects, or async callbacks without re-creating handlers. This keeps rerenders low and avoids unnecessary DOM churn in high-frequency UI paths (e.g., mass updates).

Customization, Styling & Promise toasts

Styling Sonner can be as minimal or as complete as you want. Out of the box you get basic styles; for production, you’ll often override classes or provide a custom render component. Because Sonner decouples logic from markup, you can use Tailwind, CSS modules, or styled-components without friction.

Promise toasts are particularly helpful: instead of managing loading state yourself, call toast.promise(save(), { loading: 'Saving…', success: 'Saved!', error: 'Failed to save' }). The library shows a loading toast and then updates it to success or error when the promise resolves or rejects. This reduces UI complexity and improves perceived performance.

Accessibility matters: Sonner uses ARIA live regions to announce messages to screen readers and keeps focus management straightforward. When customizing, ensure your replacements still expose the same ARIA attributes and maintain readable contrast and motion preferences.

Performance & Best Practices

To keep notifications performant, avoid re-rendering the entire provider—mount it once at the app root. Use stable handlers (useCallback) when calling toast functions from frequently rendered components to prevent creating new closures on every render.

Debounce or throttle high-frequency toasts (for example, network error floods) to avoid overwhelming users and the DOM. Keep toast lifetimes short for minor info and longer for actionable items so users can react when needed.

Quick checklist for production: keep Toaster mounted at root, use promise toasts for async flows, and ensure your styles respect reduced-motion and ARIA attributes.

  • Mount provider once, prefer hook/imperative API, and throttle repetitive toasts.

Example: Minimal Sonner usage in React

Below is a short example showing provider setup, simple toast, and a promise toast for a save action. Paste into a create-react-app or Vite project after installing Sonner.

// App.jsx
import React from 'react';
import { Toaster, toast } from 'sonner';

export default function App() {
  async function onSave() {
    const fakeSave = new Promise((res, rej) => setTimeout(res, 1200));
    toast.promise(fakeSave, {
      loading: 'Saving…',
      success: 'Saved successfully!',
      error: 'Save failed'
    });
  }

  return (
    <div>
      <button onClick={() => toast('Simple toast message')}>Toast</button>
      <button onClick={onSave}>Save (promise)</button>
      <Toaster />
    </div>
  );
}

For a deeper dive with advanced animations, stacking rules, and custom render components, see this in-depth Sonner tutorial and examples: advanced toast notifications with Sonner in React.

If you need to expose global config like default duration or placement, pass props to the <Toaster /> component at the root and keep overrides local for specific toasts.

FAQ

1. How do I install Sonner in a React project?

Run npm install sonner or yarn add sonner, then add <Toaster /> to your app root and call toast('message') or use toast.promise for async flows.

2. Can Sonner handle promise-based toasts?

Yes—use toast.promise(promise, { loading, success, error }). It manages the lifecycle automatically, replacing the loading toast with success or error when the promise resolves or rejects.

3. How do I customize Sonner’s styling and behavior?

Override default classes or provide a custom toast renderer; you can use any styling approach (Tailwind, CSS modules, styled-components). Keep ARIA attributes and reduced-motion preferences intact for accessibility.

Semantic Core (keyword clusters)

Primary Secondary Clarifying / Long-tail
sonner
React toast notifications
sonner tutorial
React notification library
sonner installation
React toast messages
sonner setup
React alert notifications
React toast hooks
sonner customization
React notification system
sonner promise
React toast library
toast provider React
promise-based toast React
accessible toast notifications
toast positioning and stacking
“how to install sonner in react” (voice search)