Sonner: React Toast Notifications — Guide, Setup & Examples
Practical, example-driven guide to install, configure and customize Sonner in React apps — with promise toasts, hooks and accessibility tips.
Quick SERP analysis (top-10, English)
Search intent across the provided keywords is overwhelmingly informational and transactional with a technical tilt. Results you’ll typically find in top-10: the official docs / GitHub repo, npm package page, quick-start blog posts, code examples (Stack Overflow, Dev.to, personal blogs), and comparison posts listing alternatives (react-toastify, react-hot-toast, notistack).
User intents by keyword:
- Informational: “sonner tutorial”, “sonner example”, “React toast messages”, “React toast hooks”, “sonner customization”. Users want how-to, examples, and API explanations.
- Transactional/Commercial: “React notification library”, “React toast library”, “React notification system” — users evaluate and compare libraries before choosing one.
- Navigation: “sonner”, “sonner setup”, “sonner installation” — often they aim to find the official docs or npm/GitHub pages.
- Mixed: “sonner promise” — both informational (how it works) and practical (how to implement promise-based toasts).
Typical competitor structure and depth:
- Official docs: short installation, quick-start example, API reference, customization & theming guide, SSR notes.
- Blog tutorials: step-by-step setup, promise toasts, custom components, integration with Next.js/TypeScript, animation notes.
- Comparisons: tables showing bundle size, accessibility, TypeScript support, features (promise, hooks, stacking, pause on hover).
Expanded semantic core (clusters)
- sonner
- React toast notifications
- sonner tutorial
- React notification library
- sonner installation
- sonner setup
- sonner example
- React toast messages
- sonner customization
- sonner promise
- React toast hooks
- React alert notifications
- React notification system
- toast, toasts, notifier, snackbar
- toast positioning, stacking, auto-dismiss
- promise-based toast, toast.promise, async notifications
- useToast, Toaster component, provider
- accessibility aria-live, keyboard dismiss
- TypeScript, Next.js integration, SSR-safe toasts
- custom content, custom animations, theme variables
Usage note: apply primary keywords in title and H1, sprinkle secondary and LSI naturally across sections and code examples; avoid repetitive exact-match stuffing.
Key references & backlinks
Official pages and useful guides (anchor text linked from keywords):
- sonner (npm) — installation and package info
- sonner (GitHub repo) — source, issues, examples
- sonner tutorial — advanced toasts (Dev.to) — practical walkthrough (provided source)
What Sonner is — and why it often wins a shortlist
Sonner is a compact React toast library that focuses on minimal API, predictable behavior and customizability. It takes the familiar Toaster + toast API pattern (exposed as components and functions) and keeps the surface area small while enabling common needs: promise toasts, custom content, theming and accessibility.
Why choose Sonner over a more established alternative? Typically for one or more of these reasons: small footprint, sane defaults (positioning, stacking, dismissal), a developer-friendly API that maps to patterns most React developers already expect, and first-class support for promise-based flows. If you appreciate ergonomic APIs and don’t want to fight styling or tabindex issues, Sonner is worth evaluating.
That said: pick libraries based on your constraints. If your team requires a highly opinionated enterprise-grade notification system with integrated queuing and analytics, you’ll supplement Sonner with glue code. For most apps though — admin UIs, dashboards, marketing pages — Sonner is a tidy winner.
Installation and minimal setup
Install via npm or yarn. This is a single dependency step — the common gate to get to working toasts. Example:
npm install sonner
# or
yarn add sonner
Once installed, add the Toaster component near the root of your app — typically in App.jsx or at a layout level for Next.js. This component renders the toast container and manages lifecycle. Minimal example:
import React from 'react';
import { Toaster, toast } from 'sonner';
function App() {
return (
<div>
<Toaster />
<button onClick={() => toast('Hello from Sonner!')}>Notify</button>
</div>
);
}
Placing Toaster once avoids duplicated containers and ensures global control. If your app uses multiple roots (micro-frontends, portals), mount a Toaster per root that needs notifications. Otherwise, keep it centralized to avoid unpredictable stacking.
Basic usage, hooks and everyday patterns
Most usage revolves around the global toast helper and the Toaster component. The helper exposes syntactic sugar for severity (success, error, loading) and lets you pass strings, JSX, or custom components. This permits concise notifications as well as rich interactive toasts (buttons, links).
For component-driven notifications, you can provide custom JSX as content. This is perfect when you need a CTA inside the toast (e.g., “Undo”). Programmatic control (update/dismiss) is typically done by keeping the toast id returned by the call and then invoking the appropriate method to update or dismiss it.
If Sonner exposes a hook like useToast (common in modern libs), use it for scoped providers and testing. Hooks make it easy to encapsulate notification logic (e.g., centralized error handler) without sprinkling global imports around your codebase.
Promise toasts — turning async into UX
Promise toasts are the small convenience that make async flows feel polished. The idea: show a “loading” toast while a promise runs, then automatically update it to success or error depending on outcome. This avoids flash-of-loading states and keeps users informed without extra state boilderplate.
Typical API is a single call wrapping your promise and providing messages for each state. Example pattern (pseudocode):
const promise = fetchData();
toast.promise(promise, {
loading: 'Loading items…',
success: 'Loaded!',
error: 'Failed to load'
});
Behind the scenes the library keeps a reference to the toast ID, swaps content and optionally changes styles. The UX result is clean: one toast mirrors the promise lifecycle rather than multiple toasts bouncing in and out.
Customization and theming
Sonner generally exposes props/options for global defaults (position, duration, close button) and per-toast overrides (autoClose, pauseOnHover). The customization model often uses CSS variables or component-level props so you can inject design tokens from your theme provider.
For deeper changes — custom animations, layout changes, or entirely custom toast markup — use a custom render function or pass JSX into the toast call. Combine this with your CSS-in-JS or stylesheets to match brand guidelines. Keep accessibility in mind: maintain clear text, meaningful action labels and respect prefers-reduced-motion for animations.
Tip: centralize your toast options in one file (e.g., toastConfig.js) so updates (timing, positions) propagate app-wide. That avoids accidental inconsistent UX when multiple developers add raw options inline.
Best practices & accessibility
Accessibility is often an afterthought for toasts, but Sonner typically supports aria-live regions, proper role attributes and keyboard dismissal hooks. Ensure screen readers get concise, meaningful messages and avoid overloading them with status updates for events that aren’t relevant.
Limit toast frequency for users — batch messages where possible. A barrage of notifications is both annoying and harmful for assistive tech. Prefer aggregated toasts for bulk operations (e.g., “10 files uploaded — 2 failed”).
Finally, test in varied contexts: slow networks, screen readers, and mobile devices. Pay attention to stacking behavior on small screens and interactions with fixed-position elements.
Common user questions (collected)
Top related user questions found across People Also Ask, forums and documentation pages:
- How do I install and set up Sonner in a React project?
- How can I customize the look and behavior of Sonner toasts?
- Does Sonner support promise-based toasts and how do I use them?
- How to render custom JSX inside a toast?
- Is Sonner accessible and SSR-friendly (Next.js)?
- Can I programmatically dismiss or update a toast?
- How does Sonner compare to react-toastify or react-hot-toast?
FAQ
How do I install and set up Sonner in a React project?
Install with npm install sonner or yarn add sonner. Add <Toaster /> near your app root and call toast('Message') from components. See the official npm and repo pages for up-to-date APIs: sonner (npm), sonner (GitHub).
How can I customize Sonner toasts (styles, position, duration)?
Use global Toaster props (position, default duration) and per-toast options for overrides. For visual changes, pass custom JSX or provide theme variables/CSS to override the default styles. Respect prefers-reduced-motion for animations and centralize config for consistency.
Does Sonner support promise-based toasts and how do I use them?
Yes — Sonner (like many modern toast libs) supports a promise helper that shows a loading toast while the promise resolves, then updates to success or error automatically. Typical usage: toast.promise(fetchData(), { loading: 'Loading', success: 'Done', error: 'Failed' }). Check docs for exact API and customization options.
SEO, voice search and snippet readiness
To target voice search and featured snippets:
- Include short, direct answers near the top of sections (1–2 sentences) for quick reads by assistants.
- Use code blocks for “how-to” steps that can appear as code snippets in search results.
- Embed FAQ schema (done above) so Google can surface quick answers.
If you want, I can: produce a TypeScript-ready example, add Next.js SSR notes, build a side-by-side comparison table with react-toastify and react-hot-toast, or output a trimmed version optimized for a specific CMS. Which would you like next?
