Next.js toast notifications

The one thing to get right in Next.js is where the Toaster lives. It uses React hooks, so it has to be in a client component. Everything else is the same as plain React.

Try it:

Install

npm i @yusufceng1z/ding-react

A client component for the Toaster

Create components/toaster.tsx:

"use client";

      import { Toaster } from '@yusufceng1z/ding-react';

      export function AppToaster() {
        return <Toaster position="top-center" theme="system" />;
      }

Then render it once in app/layout.tsx. The layout itself can stay a server component.

import { AppToaster } from '@/components/toaster';

      export default function RootLayout({ children }: { children: React.ReactNode }) {
        return (
          <html lang="en">
            <body>
              {children}
              <AppToaster />
            </body>
          </html>
        );
      }

Call toast from client code

"use client";

      import { toast } from '@yusufceng1z/ding-react';

      export function SaveButton() {
        return <button onClick={() => toast.success('Saved')}>Save</button>;
      }

Server actions

toast runs in the browser, so it cannot be called inside a server action. Call it from the client code that triggers the action and pass the action's promise:

toast.promise(saveAction(formData), {
        loading: 'Saving…',
        success: 'Saved',
        error: 'Could not save',
      });

If the project already uses shadcn/ui, the shadcn install does the wrapper file for you. For the non-Next parts see React toast notifications.