Skip to content
Twilight React Playground
ثيم رائدaren

useToast

functionBeginnerbrowserlive demo

Another name for toast: the same object, not a React hook, so there is nothing to call at the top of a component.

import { useToast } from '@salla.sa/twilight-theme-engine/components/toast';

In plain words

useToast looks like a hook (a function whose name starts with use, called at the top of a component), but it is not one. It is exactly the same object as toast, exported under a second name.

So there is no const toast = useToast() step: call its methods directly, useToast.success('Saved'), from a click handler. Importing it as toast instead reads better and avoids the confusion.

Signature

const useToast: ToastFn   // the very same object as toast

// useToast === toast  →  true

Try it live

useToast and toast are one and the same object, imported under two names.Try this: press the button twice: each call shows a toast and returns a new id.
Storefront canvas · ar · RTL

useToast === toast is true

Controls
What a theme writes
import { toast } from '@salla.sa/twilight-theme-engine/components/toast';

export function ApplyCouponButton() {
  // Prefer the name toast: calling useToast(…) inside a handler trips the hooks lint rule.
  return (
    <button type="button" className="btn btn--primary" onClick={() => toast.info('Your coupon was applied')}>
      Apply
    </button>
  );
}

Example

app/components/cart/ApplyCouponButton.tsx
import { useToast } from '@salla.sa/twilight-theme-engine/components/toast';

export function ApplyCouponButton({ apply }: { apply: () => Promise<void> }) {
  const onClick = async () => {
    try {
      await apply();
      useToast.success('Coupon applied'); // a method call, not a hook call
    } catch {
      useToast.error('This coupon is not valid');
    }
  };

  return (
    <button type="button" className="btn btn--primary" onClick={onClick}>
      Apply
    </button>
  );
}

How it behaves

  • The source is export const useToast: ToastFn = Object.assign(…) followed by export { useToast as toast } (useToast.ts). It uses no React API, so the rules of hooks do not apply to it.

  • Everything on the toast page applies, including the broken update().

Gotchas

  • docs/18-hooks-api.md shows const toast = useToast(); then toast.promise(…). TypeScript rejects the call (the title is required). In plain JavaScript it shows an empty toast on every render and returns a number (the new toast's id), so toast.promise throws TypeError: toast.promise is not a function. Call the methods on the import itself.

  • Calling it directly, useToast('Saved'), inside an event handler fails ESLint's react-hooks/rules-of-hooks rule ("React Hook useToast cannot be called inside a callback") in any theme that enables it, as the twilight-platform repository does, only because of the name. Method calls like useToast.success('Saved') pass, and so does anything on the toast import.

Related

Source and docs