### Basic SnackbarProvider Setup
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Set up the `SnackbarProvider` to manage snackbars. This basic setup does not require children, and snackbars render as siblings. The `enqueueSnackbar` function can be called directly after the provider is mounted.
```tsx
import { SnackbarProvider, enqueueSnackbar } from 'notistack';
// Basic setup — no children required; snackbars render as siblings
const App = () => (
);
```
```tsx
// With children — every descendant can use useSnackbar()
const AppWithChildren = () => (
);
```
--------------------------------
### Basic SnackbarProvider Usage
Source: https://github.com/iamhosseindhv/notistack/blob/master/README.md
Wrap your application with SnackbarProvider and use enqueueSnackbar to display notifications. This is the most straightforward way to get started.
```jsx
import { SnackbarProvider, enqueueSnackbar } from 'notistack';
const App = () => {
return (
);
};
```
--------------------------------
### Install Notistack
Source: https://github.com/iamhosseindhv/notistack/blob/master/README.md
Install notistack using npm or yarn. This is the first step to integrate notifications into your application.
```bash
npm install notistack
yarn add notistack
```
--------------------------------
### Create a minimal custom snackbar component
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Build a custom snackbar component using `SnackbarContent` as a low-level primitive. This example demonstrates forwarding a ref and implementing a custom close button with variant-specific background colors.
```tsx
import { forwardRef } from 'react';
import { SnackbarContent, CustomContentProps, useSnackbar } from 'notistack';
const MinimalCustomSnackbar = forwardRef(
({ id, message, variant }, ref) => {
const { closeSnackbar } = useSnackbar();
const colors: Record = {
success: 'green', error: 'red', warning: 'orange', info: 'blue', default: '#333',
};
return (
{message}
);
}
);
```
--------------------------------
### Implement custom enter/exit animations with Transition component
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Utilize the `Transition` component to create custom enter and exit animations for snackbars. This example shows a `FadeTransition` component that can be applied globally via `SnackbarProvider` or per-snackbar using `enqueueSnackbar`.
```tsx
import { Transition } from 'notistack';
import type { TransitionComponentProps } from 'notistack';
// Custom fade transition component
const FadeTransition: React.FC = ({ in: inProp, children, timeout, nodeRef }) => (
{(state, childProps) =>
children(state, {
...childProps,
style: {
opacity: state === 'entered' ? 1 : 0,
transition: 'opacity 300ms ease',
...(state === 'exited' && { display: 'none' }),
},
})
}
);
// Use the custom transition globally
const App = () => (
);
// Or per-snackbar
enqueueSnackbar('Hello with fade', {
TransitionComponent: FadeTransition,
transitionDuration: { enter: 400, exit: 250 },
});
```
--------------------------------
### Custom Snackbar Components with `Components` Prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Register custom React components for any snackbar variant using the `Components` prop on `SnackbarProvider`. Custom components must be wrapped with `React.forwardRef` and receive `CustomContentProps`. This example defines and uses a 'reportComplete' variant.
```tsx
import React, { forwardRef } from 'react';
import { SnackbarProvider, SnackbarContent, CustomContentProps, useSnackbar } from 'notistack';
// 1. Declare the custom variant in TypeScript
declare module 'notistack' {
interface VariantOverrides {
reportComplete: true;
}
}
// 2. Build the custom component
const ReportComplete = forwardRef(({ id, message }, ref) => {
const { closeSnackbar } = useSnackbar();
return (
{message}
);
});
ReportComplete.displayName = 'ReportComplete';
// 3. Register and use
const App = () => (
);
// 4. Enqueue with the custom variant
enqueueSnackbar("Your report is ready to download", {
variant: 'reportComplete',
persist: true,
});
```
--------------------------------
### Use `useSnackbar` Hook in Functional Components
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
The `useSnackbar` hook provides `enqueueSnackbar` and `closeSnackbar` from the nearest `SnackbarProvider`. The component must be a descendant of `SnackbarProvider`. This example demonstrates handling save operations with loading and success/error feedback.
```tsx
import { useSnackbar } from 'notistack';
const SaveButton = () => {
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const handleSave = async () => {
const loadingKey = enqueueSnackbar('Saving...', { persist: true, variant: 'info' });
try {
await saveData();
closeSnackbar(loadingKey);
enqueueSnackbar('Saved!', { variant: 'success', autoHideDuration: 2000 });
} catch (err) {
closeSnackbar(loadingKey);
enqueueSnackbar(`Error: ${err.message}`, { variant: 'error', persist: true });
}
};
return ;
};
```
--------------------------------
### `Transition` component
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
A finite-state-machine transition component for building custom enter/exit animations, managing states and providing render-prop children.
```APIDOC
## `Transition` component
A low-level finite-state-machine transition component exported for building custom enter/exit animations. It manages four states (`entering`, `entered`, `exiting`, `exited`) and calls a render-prop children function with the current state. The built-in `Slide` and `Collapse` animations are built on top of this component. Custom transitions passed as `TransitionComponent` on the provider or individual snackbars must accept `TransitionProps`.
```tsx
import { Transition } from 'notistack';
import type { TransitionComponentProps } from 'notistack';
// Custom fade transition component
const FadeTransition: React.FC = ({ in: inProp, children, timeout, nodeRef }) => (
{(state, childProps) =>
children(state, {
...childProps,
style: {
opacity: state === 'entered' ? 1 : 0,
transition: 'opacity 300ms ease',
...(state === 'exited' && { display: 'none' }),
},
})
}
);
// Use the custom transition globally
const App = () => (
);
// Or per-snackbar
enqueueSnackbar('Hello with fade', {
TransitionComponent: FadeTransition,
transitionDuration: { enter: 400, exit: 250 },
});
```
```
--------------------------------
### Enqueue Snackbar with Options
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Display a new snackbar notification using `enqueueSnackbar`. This function can be called from anywhere after `SnackbarProvider` is mounted. It returns a unique `SnackbarKey`. Options include `variant`, `persist`, `autoHideDuration`, `onClose`, and `action` for custom buttons.
```tsx
import { enqueueSnackbar, closeSnackbar } from 'notistack';
// Simple string message with variant
const key1 = enqueueSnackbar('File saved successfully', { variant: 'success' });
// With autoHideDuration override and persist
const key2 = enqueueSnackbar('Uploading...', {
variant: 'info',
persist: true, // stays until manually closed
key: 'upload-progress', // deterministic key to reference later
});
// Close by key when done
closeSnackbar('upload-progress');
// JSX as message
enqueueSnackbar(Visit docs, { variant: 'default' });
// Object-style call (alternative signature)
enqueueSnackbar({
message: 'Network error',
variant: 'error',
autoHideDuration: 8000,
onClose: (event, reason, key) => {
console.log(`Snackbar ${key} closed due to: ${reason}`);
// reason: 'timeout' | 'maxsnack' | 'instructed'
},
});
// With an action button
const key3 = enqueueSnackbar('Item deleted', {
variant: 'warning',
action: (key) => (
),
});
```
--------------------------------
### Snackbar Transition Callbacks
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Use onEnter, onEntered, onExit, and onExited callbacks to hook into the snackbar's transition lifecycle. These can be set globally on SnackbarProvider or per-snackbar via enqueueSnackbar options. Provider-level and per-snackbar callbacks are chained.
```tsx
import { SnackbarProvider, enqueueSnackbar } from 'notistack';
const App = () => (
console.log(`[global] entering ${key}`)}
onEntered={(node, isAppearing, key) => console.log(`[global] entered ${key}`)}
onExit={(node, key) => console.log(`[global] exiting ${key}`)}
onExited={(node, key) => console.log(`[global] exited and unmounted ${key}`)}
>
);
// Per-snackbar callbacks
enqueueSnackbar('Tracked notification', {
variant: 'info',
onEntered: (node, isAppearing, key) => {
analytics.track('snackbar_shown', { key });
},
onExited: (node, key) => {
analytics.track('snackbar_dismissed', { key });
},
});
```
--------------------------------
### SnackbarProvider - domRoot prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Renders all snackbars into a specific DOM node via `ReactDOM.createPortal` instead of inline within the provider's normal document position. Useful for escaping CSS stacking contexts or rendering into a custom layer.
```APIDOC
## `SnackbarProvider` — `domRoot` prop (portal rendering)
### Description
Renders all snackbars into a specific DOM node via `ReactDOM.createPortal` instead of inline within the provider's normal document position. Useful for escaping CSS stacking contexts (e.g., modal overlays) or rendering into a custom layer.
### Usage
```tsx
import { useRef, useEffect } from 'react';
import { SnackbarProvider, enqueueSnackbar } from 'notistack';
const App = () => {
const portalRef = useRef(null);
return (
<>
{/* Portal target must be rendered before SnackbarProvider uses it */}
>
);
};
```
```
--------------------------------
### Portal Rendering with `domRoot` Prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Render snackbars into a specific DOM node using `ReactDOM.createPortal` by providing the `domRoot` prop to `SnackbarProvider`. This is useful for managing CSS stacking contexts or rendering into custom layers. The target DOM node must exist before `SnackbarProvider` mounts.
```tsx
import { useRef, useEffect } from 'react';
import { SnackbarProvider, enqueueSnackbar } from 'notistack';
const App = () => {
const portalRef = useRef(null);
return (
<>
{/* Portal target must be rendered before SnackbarProvider uses it */}
>
);
};
```
--------------------------------
### Apply custom CSS classes to snackbar containers and roots
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Use the `classes` prop on `SnackbarProvider` to apply custom CSS class names to the snackbar container and individual snackbar elements. Supported class keys include `containerRoot` and `root`, along with position-specific variants.
```tsx
import { SnackbarProvider } from 'notistack';
import styles from './notifications.module.css';
// notifications.module.css:
// .snackContainer { z-index: 9999; }
// .snackRoot { border-radius: 8px; min-width: 320px; }
const App = () => (
);
```
--------------------------------
### Migrate from withSnackbar HOC to functional components or direct imports
Source: https://github.com/iamhosseindhv/notistack/blob/master/MIGRATION.md
The `withSnackbar` Higher-Order Component (HOC) is no longer supported in v2. Migrate to functional components using the `useSnackbar` hook or import `enqueueSnackbar` and `closeSnackbar` directly.
```diff
```diff
- import { withSnackbar } from 'notistack'
+ import { enqueueSnackbar, closeSnackbar } from 'notistack'
class MyButton extends React.Component {
render() {
- const { enqueueSnackbar } = this.props
}
}
- export default withSnackbar(MyButton)
+ export default MyButton
```
```
--------------------------------
### Define custom snackbar variants using the Components prop
Source: https://github.com/iamhosseindhv/notistack/blob/master/MIGRATION.md
Use the `Components` prop on `SnackbarProvider` to define custom snackbar variants. Custom components receive all props passed to `enqueueSnackbar` and `SnackbarProvider`, along with custom props.
```tsx
```tsx
interface ReportCompleteProps extends CustomContentProps {
allowDownload: boolean;
}
const ReportComplete = React.forwardRef((props: ReportCompleteProps, ref) => {
const {
// You have access to notistack props, options 👇🏼
variant,
message
// as well as your own custom props 👇🏼
allowDownload,
} = props;
//
})
enqueueSnackbar('Your report is ready to download', {
variant: 'reportComplete',
persist: true,
allowDownload: true, // <-- pass any additional options
})
```
```
--------------------------------
### SnackbarProvider Configuration
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
The SnackbarProvider component must wrap your application to manage snackbar notifications. It accepts several props to customize behavior and appearance.
```APIDOC
## SnackbarProvider
The root provider component that must wrap any part of your application that needs to show snackbars. It initializes the internal queue, exposes the context, and renders all active snackbars into a positioned container. When mounted, it also binds the module-level `enqueueSnackbar` and `closeSnackbar` singletons, allowing usage from outside React components.
### Props:
- **maxSnack** (number) - Optional - Maximum simultaneously visible snackbars. Default: `3`
- **anchorOrigin** ({ vertical, horizontal }) - Optional - Position of the snackbar container. Default: `{ vertical: 'bottom', horizontal: 'left' }`
- **autoHideDuration** (number | null) - Optional - Time in ms before auto-close; `null` disables it. Default: `5000`
- **dense** (boolean) - Optional - Reduces spacing (useful on mobile). Default: `false`
- **preventDuplicate** (boolean) - Optional - Suppresses duplicate messages. Default: `false`
- **domRoot** (HTMLElement) - Optional - Portal target element.
- **Components** (Record) - Optional - Custom components per variant.
- **iconVariant** (Partial>) - Optional - Override icons per variant.
- **classes** (Partial) - Optional - CSS class overrides for container and snackbar root.
### Example Usage:
```tsx
import { SnackbarProvider } from 'notistack';
const App = () => (
{/* Your app components */}
);
```
```
--------------------------------
### SnackbarProvider - Components prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Register fully custom React components for any variant (built-in or user-defined). Each custom component receives `CustomContentProps` and must be wrapped with `React.forwardRef`. This allows complete control over layout, styling, and interactive content.
```APIDOC
## `SnackbarProvider` — `Components` prop (custom snackbar components)
### Description
Register fully custom React components for any variant (built-in or user-defined). Each custom component receives `CustomContentProps` and must be wrapped with `React.forwardRef`. This allows complete control over layout, styling, and interactive content (e.g., expandable cards, download buttons, theme-aware rendering).
### Usage
```tsx
import React, { forwardRef } from 'react';
import { SnackbarProvider, SnackbarContent, CustomContentProps, useSnackbar } from 'notistack';
// 1. Declare the custom variant in TypeScript
declare module 'notistack' {
interface VariantOverrides {
reportComplete: true;
}
}
// 2. Build the custom component
const ReportComplete = forwardRef(({ id, message }, ref) => {
const { closeSnackbar } = useSnackbar();
return (
{message}
);
});
ReportComplete.displayName = 'ReportComplete';
// 3. Register and use
const App = () => (
);
// 4. Enqueue with the custom variant
enqueueSnackbar("Your report is ready to download", {
variant: 'reportComplete',
persist: true,
});
```
```
--------------------------------
### `SnackbarContent`
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
A low-level layout primitive used as the outermost wrapper in custom snackbar components, allowing custom components to forward a ref.
```APIDOC
## `SnackbarContent`
A low-level layout primitive — a `forwardRef` `div` — used as the outermost wrapper in custom snackbar components. It is exported so custom components can forward a ref to a stable DOM node (required by notistack's internal transition system).
```tsx
import { forwardRef } from 'react';
import { SnackbarContent, CustomContentProps, useSnackbar } from 'notistack';
const MinimalCustomSnackbar = forwardRef(
({ id, message, variant }, ref) => {
const { closeSnackbar } = useSnackbar();
const colors: Record = {
success: 'green', error: 'red', warning: 'orange', info: 'blue', default: '#333',
};
return (
{message}
);
}
);
```
```
--------------------------------
### `SnackbarProvider` `classes` prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Applies custom CSS class names to the container and individual snackbar elements for styling.
```APIDOC
## `SnackbarProvider` `classes` prop (CSS overrides)
Applies custom CSS class names to the container and individual snackbar elements. Supported class keys for the container: `containerRoot`, `containerAnchorOriginTopLeft`, `containerAnchorOriginTopCenter`, `containerAnchorOriginTopRight`, `containerAnchorOriginBottomLeft`, `containerAnchorOriginBottomCenter`, `containerAnchorOriginBottomRight`. Snackbar root keys mirror the same positions without the `container` prefix.
```tsx
import { SnackbarProvider } from 'notistack';
import styles from './notifications.module.css';
// notifications.module.css:
// .snackContainer { z-index: 9999; }
// .snackRoot { border-radius: 8px; min-width: 320px; }
const App = () => (
);
```
```
--------------------------------
### Snackbar onClose Callback
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
The onClose callback fires before a snackbar is removed. It receives the event, a reason ('timeout', 'maxsnack', or 'instructed'), and the snackbar key. This can be configured globally or per-snackbar.
```tsx
import { enqueueSnackbar, SnackbarProvider } from 'notistack';
import type { CloseReason, SnackbarKey } from 'notistack';
const App = () => (
{
if (reason === 'maxsnack') {
console.warn(`Snackbar ${key} was auto-closed to make room for a new one`);
}
}}
>
);
// Per-snackbar onClose
enqueueSnackbar('Changes saved', {
variant: 'success',
onClose: (event, reason, key) => {
if (reason === 'timeout') {
logEvent('snackbar_timeout', { key });
}
},
});
```
--------------------------------
### Using useSnackbar Hook
Source: https://github.com/iamhosseindhv/notistack/blob/master/README.md
Utilize the useSnackbar hook for displaying snackbars within functional components. Ensure your app is wrapped in SnackbarProvider to access the hook.
```jsx
import { SnackbarProvider, useSnackbar } from 'notistack';
// wrap your app
const MyButton = () => {
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
return ;
};
```
--------------------------------
### Customize snackbar appearance with MaterialDesignContent
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Extend the default `MaterialDesignContent` component using `styled-components` to customize variant-specific background colors and font sizes. This allows for a consistent and branded look across different snackbar types.
```tsx
import { SnackbarProvider, MaterialDesignContent } from 'notistack';
import styled from 'styled-components';
// Extend the default appearance with styled-components
const StyledMaterialDesignContent = styled(MaterialDesignContent)(() => ({
'&.notistack-MuiContent-success': {
backgroundColor: '#2D7738',
fontSize: '1rem',
},
'&.notistack-MuiContent-error': {
backgroundColor: '#970C0C',
},
}));
const App = () => (
);
```
--------------------------------
### `MaterialDesignContent`
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
The default snackbar content component. It can be exported and used as a base for customisation by overriding individual variant slots.
```APIDOC
## `MaterialDesignContent`
The default snackbar content component used internally. It renders a styled `div` with variant-specific background colors (success: `#43a047`, error: `#d32f2f`, warning: `#ff9800`, info: `#2196f3`, default: `#313131`), an optional icon, the message, and an optional action area. It can be exported and used as a base for customisation by overriding individual variant slots in the `Components` prop.
```tsx
import { SnackbarProvider, MaterialDesignContent } from 'notistack';
import styled from 'styled-components';
// Extend the default appearance with styled-components
const StyledMaterialDesignContent = styled(MaterialDesignContent)(() => ({
'&.notistack-MuiContent-success': {
backgroundColor: '#2D7738',
fontSize: '1rem',
},
'&.notistack-MuiContent-error': {
backgroundColor: '#970C0C',
},
}));
const App = () => (
);
```
```
--------------------------------
### enqueueSnackbar Function
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Displays a new snackbar notification. This function is available as a named export from 'notistack' after a SnackbarProvider has been mounted and can be called from anywhere.
```APIDOC
## enqueueSnackbar (module-level singleton)
Displays a new snackbar notification. This function is available directly as a named export from `notistack` after a `SnackbarProvider` has been mounted. It can be called from anywhere: Redux thunks, async functions, event handlers, utilities — not just inside React components. Returns the unique `SnackbarKey` for the new notification.
### Parameters:
- **message** (string | ReactNode) - The message to display in the snackbar.
- **options** (object) - Optional configuration options for the snackbar.
- **variant** (string) - The variant of the snackbar ('default', 'success', 'error', 'warning', 'info').
- **persist** (boolean) - If true, the snackbar will not auto-hide.
- **key** (string | number) - A deterministic key to reference the snackbar.
- **autoHideDuration** (number | null) - Time in ms before auto-close.
- **onClose** (function) - Callback function when the snackbar is closed.
- **action** (function) - A function that returns a ReactNode to be displayed as an action (e.g., a button).
### Example Usage:
```tsx
import { enqueueSnackbar, closeSnackbar } from 'notistack';
// Simple string message with variant
const key1 = enqueueSnackbar('File saved successfully', { variant: 'success' });
// With autoHideDuration override and persist
const key2 = enqueueSnackbar('Uploading...', {
variant: 'info',
persist: true,
key: 'upload-progress'
});
// JSX as message
enqueueSnackbar(Visit docs, { variant: 'default' });
// Object-style call
enqueueSnackbar({
message: 'Network error',
variant: 'error',
autoHideDuration: 8000,
onClose: (event, reason, key) => {
console.log(`Snackbar ${key} closed due to: ${reason}`);
}
});
// With an action button
const key3 = enqueueSnackbar('Item deleted', {
variant: 'warning',
action: (key) => (
)
});
```
```
--------------------------------
### Redux Integration for Snackbars
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Integrate notistack with Redux by dispatching snackbar actions (enqueue, close) through the store. A notifier component processes these actions to display or dismiss snackbars.
```javascript
// redux/actions.js
export const ENQUEUE_SNACKBAR = 'ENQUEUE_SNACKBAR';
export const CLOSE_SNACKBAR = 'CLOSE_SNACKBAR';
export const REMOVE_SNACKBAR = 'REMOVE_SNACKBAR';
export const enqueueSnackbar = (notification) => ({
type: ENQUEUE_SNACKBAR,
notification: { key: new Date().getTime() + Math.random(), ...notification },
});
export const closeSnackbar = (key) => ({ type: CLOSE_SNACKBAR, dismissAll: !key, key });
export const removeSnackbar = (key) => ({ type: REMOVE_SNACKBAR, key });
```
```javascript
// useNotifier.js
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSnackbar } from 'notistack';
import { removeSnackbar } from './redux/actions';
const useNotifier = () => {
const dispatch = useDispatch();
const notifications = useSelector((store) => store.notifications.notifications || []);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
useEffect(() => {
notifications.forEach(({ key, message, options = {}, dismissed = false }) => {
if (dismissed) {
closeSnackbar(key);
return;
}
enqueueSnackbar(message, { key, ...options, onExited: (_, myKey) => dispatch(removeSnackbar(myKey)) });
});
}, [notifications]);
};
// In App.js
const App = () => {
useNotifier();
const dispatch = useDispatch();
return (
);
};
```
--------------------------------
### Dismiss Snackbars Programmatically with `closeSnackbar`
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Use `closeSnackbar` to dismiss specific snackbars by key or all active snackbars. This function triggers the `onClose` callback with `reason: 'instructed'`. Ensure `enqueueSnackbar` and `closeSnackbar` are imported from 'notistack'.
```tsx
import { enqueueSnackbar, closeSnackbar } from 'notistack';
// Dismiss a specific snackbar by key
const key = enqueueSnackbar('Processing...', { persist: true, variant: 'info' });
setTimeout(() => closeSnackbar(key), 5000);
// Dismiss all snackbars at once (e.g., on logout / route change)
function onUserLogout() {
closeSnackbar();
redirectToLogin();
}
```
--------------------------------
### Migrate HTML attributes to SnackbarProps
Source: https://github.com/iamhosseindhv/notistack/blob/master/MIGRATION.md
Pass HTML attributes to the Snackbar root component via the `SnackbarProps` prop. This change applies to both `SnackbarProvider` and `enqueueSnackbar` calls.
```diff
```diff
enqueueSnackbar('message', {
- 'data-test': 'test',
+ SnackbarProps: {
+ 'data-test': 'test',
+ },
})
```
```
--------------------------------
### closeSnackbar
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Programmatically dismisses a snackbar. When called with a SnackbarKey, that specific snackbar is closed. When called with no argument, all active snackbars are dismissed. Triggers the onClose callback of the targeted snackbar(s) with reason: 'instructed'.
```APIDOC
## `closeSnackbar` (module-level singleton)
### Description
Programmatically dismisses a snackbar. When called with a `SnackbarKey`, that specific snackbar is closed. When called with no argument, **all** active snackbars are dismissed. Triggers the `onClose` callback of the targeted snackbar(s) with `reason: 'instructed'`.
### Usage
```tsx
import { enqueueSnackbar, closeSnackbar } from 'notistack';
// Dismiss a specific snackbar by key
const key = enqueueSnackbar('Processing...', { persist: true, variant: 'info' });
setTimeout(() => closeSnackbar(key), 5000);
// Dismiss all snackbars at once (e.g., on logout / route change)
function onUserLogout() {
closeSnackbar();
redirectToLogin();
}
```
```
--------------------------------
### useSnackbar hook
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
A React hook that returns `{ enqueueSnackbar, closeSnackbar }` from the nearest `SnackbarProvider` context. Use this inside functional React components to show and dismiss snackbars. The component must be a descendant of `SnackbarProvider`.
```APIDOC
## `useSnackbar` hook
### Description
A React hook that returns `{ enqueueSnackbar, closeSnackbar }` from the nearest `SnackbarProvider` context. Use this inside functional React components to show and dismiss snackbars. The component must be a descendant of `SnackbarProvider`.
### Usage
```tsx
import { useSnackbar } from 'notistack';
const SaveButton = () => {
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const handleSave = async () => {
const loadingKey = enqueueSnackbar('Saving...', { persist: true, variant: 'info' });
try {
await saveData();
closeSnackbar(loadingKey);
enqueueSnackbar('Saved!', { variant: 'success', autoHideDuration: 2000 });
} catch (err) {
closeSnackbar(loadingKey);
enqueueSnackbar(`Error: ${err.message}`, { variant: 'error', persist: true });
}
};
return ;
};
```
```
--------------------------------
### Override Icons with `iconVariant` Prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Customize the icons displayed for each snackbar variant using the `iconVariant` prop on `SnackbarProvider`. You can provide any `ReactNode` or set it to `null` to remove the icon. The `hideIconVariant` prop can suppress all icons.
```tsx
import { SnackbarProvider } from 'notistack';
const FireIcon = () => 🔥;
const BugIcon = () => 🐛;
const App = () => (
✅,
error: ,
warning: ,
info: ℹ️,
default: null,
}}
>
);
```
--------------------------------
### SnackbarProvider - iconVariant prop
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Overrides the icons displayed next to variant messages. Each variant maps to any `ReactNode`. Setting a variant's icon to `null` removes it. The `hideIconVariant` prop suppresses all icons.
```APIDOC
## `SnackbarProvider` — `iconVariant` prop
### Description
Overrides the icons displayed next to variant messages. Each variant maps to any `ReactNode`. Setting a variant's icon to `null` removes it. The `hideIconVariant` prop (per-snackbar or globally on the provider) suppresses all icons.
### Usage
```tsx
import { SnackbarProvider } from 'notistack';
const FireIcon = () => 🔥;
const BugIcon = () => 🐛;
const App = () => (
✅,
error: ,
warning: ,
info: ℹ️,
default: null,
}}
>
);
```
```
--------------------------------
### closeSnackbar Function
Source: https://context7.com/iamhosseindhv/notistack/llms.txt
Closes an existing snackbar notification. It can be called with the snackbar's key or it will close the most recently displayed snackbar if no key is provided.
```APIDOC
## closeSnackbar (module-level singleton)
Closes an existing snackbar notification. This function is available directly as a named export from `notistack` after a `SnackbarProvider` has been mounted. It can be called from anywhere.
### Parameters:
- **key** (string | number) - Optional. The unique `SnackbarKey` of the notification to close. If not provided, the most recently displayed snackbar will be closed.
### Example Usage:
```tsx
import { enqueueSnackbar, closeSnackbar } from 'notistack';
// Enqueue a snackbar and get its key
const key = enqueueSnackbar('This will be closed soon', { variant: 'info' });
// Close the specific snackbar using its key
setTimeout(() => closeSnackbar(key), 3000);
// Close the most recent snackbar (if multiple are open)
// closeSnackbar();
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.