UIBeginnerSSR-safehooks/ui/useToast.ts

useToast

Headless toast queue.

Import

TypeScript
import { useToast } from '@/hooks';

API

Signature

useToast(options?) → { toasts, toast, success, error, dismiss }

When to use

Use useToast instead of re-implementing the same pattern in multiple components.

SSR / Next.js

DOM extras (scroll lock, focus trap) run only in effects.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useToast
Editor
function Notify() {
  const { toasts, success, error, dismiss } = useToast();
  return (
    <div>
      <button onClick={() => success('Saved!')}>Toast</button>
      <button onClick={() => error('Failed')}>Error</button>
      <ul>
        {toasts.map((t) => (
          <li key={t.id}>
            {t.message}
            <button onClick={() => dismiss(t.id)}>x</button>
          </li>
        ))}
      </ul>
    </div>
  );
}
Preview

Implementation source

Full library source for useToast — copy into your project when you are not installing a package yet.

hooks/ui/useToast.ts
import { useCallback, useState } from 'react';

export type ToastVariant = 'info' | 'success' | 'warning' | 'error';

export interface Toast {
  id: string;
  title?: string;
  message: string;
  variant: ToastVariant;
  duration?: number;
}

export interface UseToastOptions {
  defaultDuration?: number;
  max?: number;
}

let toastUid = 0;

/** Minimal toast queue manager (headless). */
export function useToast(options: UseToastOptions = {}) {
  const { defaultDuration = 4000, max = 5 } = options;
  const [toasts, setToasts] = useState<Toast[]>([]);

  const dismiss = useCallback((id: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  const toast = useCallback(
    (
      message: string,
      opts: { title?: string; variant?: ToastVariant; duration?: number } = {},
    ) => {
      const id = `toast-${++toastUid}`;
      const item: Toast = {
        id,
        message,
        title: opts.title,
        variant: opts.variant ?? 'info',
        duration: opts.duration ?? defaultDuration,
      };
      setToasts((prev) => {
        const next = [...prev, item];
        return next.length > max ? next.slice(next.length - max) : next;
      });
      if (item.duration && item.duration > 0) {
        window.setTimeout(() => dismiss(id), item.duration);
      }
      return id;
    },
    [defaultDuration, max, dismiss],
  );

  const success = useCallback(
    (message: string, title?: string) =>
      toast(message, { title, variant: 'success' }),
    [toast],
  );
  const error = useCallback(
    (message: string, title?: string) =>
      toast(message, { title, variant: 'error' }),
    [toast],
  );
  const info = useCallback(
    (message: string, title?: string) =>
      toast(message, { title, variant: 'info' }),
    [toast],
  );
  const warning = useCallback(
    (message: string, title?: string) =>
      toast(message, { title, variant: 'warning' }),
    [toast],
  );

  const clear = useCallback(() => setToasts([]), []);

  return { toasts, toast, dismiss, clear, success, error, info, warning };
}

Copy-paste example

useToast.example.tsx
'use client';

import { useToast } from '@/hooks';

export function Notify() {
  const { toasts, success, error, dismiss } = useToast();
  return (
    <div>
      <button onClick={() => success('Saved!')}>Toast</button>
      <button onClick={() => error('Failed')}>Error</button>
      <ul>
        {toasts.map((t) => (
          <li key={t.id}>
            {t.message}
            <button onClick={() => dismiss(t.id)}>x</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: These are headless — you own the markup and styles.
  • Source of truth: open hooks/ui/useToast.ts for implementation details