You'll start by using the createNotificationContext function to create the React context, hooks, and helpers. You should create this in a file you can import throughout your application. In this example, we'll create it as lib/notifications/index.tsx.
import { createNotificationContext } from 'react-notification-provider';// You can customize the notification interface to include whatever props your notifications need to render.interface Notification { message: string; duration: number; level: 'success' | 'error';}// This function creates a React context and hooks for you so you'll want to export these.const { NotificationProvider, useNotificationQueue,} = createNotificationContext<Notification>();export { NotificationProvider, useNotificationQueue };
Now you want to wrap your application in this provider. This will allow you to use the useNotificationQueue hooks.
If you're using Next.js you should render this provider in your pages/_app file so that it's available on every page.
In this example we're rendering a components, NotificationList that will load the notification queue from the React context and render the list of notifications on the page.
In this example, <Notification /> would be your custom component that renders a notification UI component.
You can try the example by running yarn install and yarn start within the /example directory.
Testing
You can mock the notification system when using Storybook or writing tests. The createNotificationContext function returns a createMockNotificationQueue that can create a fake queue that can be passed into NotificationProvider:
In your tests you can create a queue, pass it in, and then inspect the queue to make sure events were fired. Here's an example using jest but you could do something similar with other mocking libraries, like sinon: