notistack Guide: React Material-UI Notifications & Toasts





notistack Guide: React Material-UI Notifications & Toasts


notistack Guide: React Material-UI Notifications & Toasts

A concise, practical guide to install, queue, customize and optimize notistack for React Material‑UI snackbars — with code, best practices and FAQ.

Introduction — what notistack is and why it matters

notistack is a lightweight React library that builds on Material‑UI’s Snackbar to provide stacked, queued, and easily styled toast notifications. If you need a notification system that plays nice with Material‑UI, supports a notification queue, and exposes a simple hook-based API, notistack is a pragmatic choice.

It abstracts the boilerplate of managing snackbars: you get an injectable provider, a concise hook (useSnackbar), variant types (success, error, info, warning), and convenience methods like enqueueSnackbar and closeSnackbar. This makes it ideal for apps that want consistent, accessible notifications without reinventing state management for toasts.

Throughout this article you’ll find step-by-step setup, code examples, customization patterns, accessibility notes and optimization tips — all designed to get you production-ready fast. For a deeper dive and community examples see the original walkthrough: Advanced toast notifications with notistack.

Why choose notistack for React Material‑UI notifications

notistack is opinionated but minimal: it leverages Material‑UI’s Snackbar under the hood while adding a reliable queue and stacking behavior. Where a raw Snackbar requires you to track open state and stack logic, notistack gives you a provider you wrap around your app and a global enqueue API — reducing top‑level state and re-renders.

It supports semantic variants out of the box (success/error/info/warning) and integrates with MUI theming. That means your toasts inherit your design system and can be customized via the theme or custom components. For teams using Material‑UI, that alignment is a decisive advantage over general-purpose toast libraries.

Finally, the API is hook-friendly (useSnackbar) and does not require prop drilling. Combined with methods like closeSnackbar and closeAll, you can manage individual or bulk notifications programmatically. This makes notistack suitable for everything from simple success toasts to complex, actionable alerts with dismiss and undo.

Getting started: installation and setup

Install notistack and its peer dependencies. If you’re on MUI v5 use the newest notistack; if you use v4, check compatibility first. Typical install with npm:

npm install notistack @mui/material @emotion/react @emotion/styled

Wrap your app with SnackbarProvider near the root so any component can enqueue a notification. Set a sensible maxSnack (how many to show at once) and anchorOrigin to control placement:

import { SnackbarProvider } from 'notistack';

function App() {
  return (
    <SnackbarProvider maxSnack={3} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}>
      <RootRouter />
    </SnackbarProvider>
  );
}

Now use the hook in any descendant component. The hook returns enqueueSnackbar and closeSnackbar which you can call imperatively:

import { useSnackbar } from 'notistack';

function SaveButton() {
  const { enqueueSnackbar } = useSnackbar();
  const onSave = () => enqueueSnackbar('Saved', { variant: 'success' });

  return <button onClick={onSave}>Save</button>;
}

Backlinks: Get the official library on GitHub at notistack, read Material‑UI’s Snackbar docs at React Material‑UI snackbar, and learn hooks at React hooks.

Core concepts: provider, hook, queueing and variants

The central pieces are SnackbarProvider and useSnackbar. SnackbarProvider mounts a root container for notifications and manages the queue. Its props (maxSnack, anchorOrigin, dense, preventDuplicate) control how toasts are displayed globally. The provider also accepts a custom content render prop for full control.

useSnackbar exposes enqueueSnackbar, closeSnackbar and closeAll. enqueueSnackbar accepts a message and options (variant, autoHideDuration, persist, action, onClose, key). Passing persist:true makes a notification stay until manually dismissed. A unique key lets you update or dismiss a specific toast later.

Queueing is automatic: when active toasts reach maxSnack, new ones queue and show when space frees up. If you need a FIFO or replacement behavior you can provide custom keys and call closeSnackbar explicitly. Use preventDuplicate to stop identical messages from stacking; it’s a simple guard for noisy systems.

Customization and advanced usage

notistack allows custom content either via the provider’s content prop or by passing a custom React node to enqueueSnackbar. This is how you implement actionable toasts (Undo buttons), progress indicators, or complex JSX. Styling can be done via Material‑UI’s theme overrides, sx prop, or CSS-in-JS depending on your MUI setup.

Example: adding an undo action inside a toast. The enqueueSnackbar action function receives a key so the action can close that specific toast when executed. This pattern is useful for undo flows or to expose secondary behavior.

enqueueSnackbar('Item deleted', {
  variant: 'warning',
  action: key => <button onClick={() => { undoDelete(); closeSnackbar(key); }}>Undo</button>
});

For fully custom UI, define a component and pass it to the provider’s content prop. That component receives snack data and helpers. Use this route when you need consistent layout, icons, or complex transitions for all your app toasts.

Performance, accessibility, and best practices

Keep toasts lightweight: avoid embedding heavy components inside notifications. When you need complex interactions, prefer an identifier + light UI in the toast and open a modal or drawer for the full workflow to avoid blocking rendering and keep the toast short-lived.

Accessibility: Material‑UI’s Snackbar provides proper ARIA roles by default, but when you customize content ensure interactive elements are keyboard accessible (tab order, focus management) and provide meaningful labels. If a toast requires focus, programmatically move focus and restore it afterward to avoid breaking navigation for keyboard users.

SSR and hydration: wrap the provider so it’s only mounted on the client or guard server rendering. Avoid enqueueSnackbar calls during server render. Also manage keys properly to avoid identity mismatches and unnecessary re-renders — prefer stable keys where you update notifications rather than recreating them.

Examples: basic and advanced patterns

Basic example (success toast): a small button that triggers a positive toast. This pattern is ideal for confirmations or transient feedback where you don’t need user action:

// inside a component
const { enqueueSnackbar } = useSnackbar();
enqueueSnackbar('Profile updated', { variant: 'success', autoHideDuration: 3000 });

Advanced example: a network error with retry button and persistence. The toast stays until the user either retries or dismisses it; retry triggers a network call and closes the toast on success.

enqueueSnackbar('Network error', {
  variant: 'error',
  persist: true,
  action: key => <button onClick={() => { retry(); closeSnackbar(key); }}>Retry</button>
});

Programmatically updating a toast: use a known key to replace content or change options without stacking duplicates. This is useful for progress updates (upload 20% → 40%). Use enqueueSnackbar with the same key and different message/options.

Semantic core: expanded keyword clusters and LSI phrases

Below is an expanded semantic core based on your primary queries. These clusters help guide on-page optimization, synonyms, and related search intents (install, tutorial, example, customization, hooks, queueing, comparison).

Use these terms naturally across headings, alt text, and code comments. They cover informational and commercial intents — from „how to install notistack” to „notistack vs react-toastify” style comparisons that often attract readers researching notification libraries.

  • Primary: notistack; React Material-UI notifications; React snackbar library; notistack installation; notistack tutorial; notistack setup; notistack example
  • Secondary: React toast notifications; React notification system; React Material-UI snackbar; notistack hooks; React notification queue; notistack customization; React notification library
  • Clarifying / LSI: enqueueSnackbar; SnackbarProvider; useSnackbar hook; maxSnack; autoHideDuration; persist notification; notification action/undo; preventDuplicate; notistack vs react-toastify; custom snackbar content

Tip: for featured snippets and voice search, add short, direct answers to common queries (e.g., „How to install notistack? — npm install notistack @mui/material”).

Popular user questions (collected from PAA, forums and developer Q&A)

Below are common user questions that help shape the FAQ and micro‑markup. They reflect what developers typically search for when evaluating or implementing notistack.

  • How do I install and set up notistack in a React app?
  • How do I queue notifications with notistack?
  • How can I customize the look and behavior of notistack snackbars?
  • How to use notistack hooks (useSnackbar) correctly?
  • What is the difference between notistack and react-toastify?
  • How do I add an action button like Undo inside a toast?
  • How to prevent duplicate notifications with notistack?

From the list above, three concentrated FAQ items follow with concise, actionable answers for quick consumption and snippet potential.

FAQ — top developer questions (short, actionable answers)

These three Q&A are optimized for featured snippets and voice search — short first-sentence answers, then a concise example or command.

Q: How do I install and set up notistack in a React app?

A: Install notistack and wrap your app with SnackbarProvider. Then call useSnackbar() in child components to enqueue notifications.

Quick commands and snippet:

npm install notistack @mui/material @emotion/react @emotion/styled

Wrap root: <SnackbarProvider maxSnack={3}>...</SnackbarProvider>

Q: How do I queue notifications with notistack?

A: notistack queues automatically: set maxSnack on the provider to control how many display; additional notifications wait in the queue and appear when space frees up.

If you need replacement or FIFO control, use stable keys with enqueueSnackbar(message, { key }) and programmatically call closeSnackbar(key) to manage entries.

Q: How can I customize the look and behavior of notistack snackbars?

A: Customize via the provider’s content render prop or by passing custom JSX to enqueueSnackbar. Use MUI theme overrides or sx/styles for visual adjustments.

For actions like Undo, provide an action function that receives the notification key and calls closeSnackbar(key) when appropriate.



Scroll to Top