@void-snippets/react

useAlertMessage

Toast-style alerts with auto-hide duration control.

#What it does

Manages the lifecycle of a single alert — text, severity, visibility, and auto-hide. You own the UI component; this hook owns the state.

#Signature

typescript
function useAlertMessage(autoHideDuration?: number): {
  alert:     { message: ReactNode; type: 'success' | 'info' | 'error'; isVisible: boolean };
  showAlert: (message: ReactNode | string, type?: 'success' | 'info' | 'error') => void;
  hideAlert: () => void;
}

#Parameters

ParameterTypeDefaultDescription
autoHideDurationnumber (ms)3000How long the alert stays visible. Pass 0 to never auto-hide.

#Example

tsx
function ContactFormPage() {
  const { alert, showAlert, hideAlert } = useAlertMessage(4000);

  const handleSubmit = async (data: Contact.Apis.Create) => {
    const [err] = await catchError(ContactsApis.create(data));
    if (err) showAlert(err.message, 'error');
    else     showAlert('Contact created!', 'success');
  };

  return (
    <>
      {alert.isVisible && (
        <div className={`alert alert-${alert.type}`}>
          {alert.message}
          <button onClick={hideAlert}>✕</button>
        </div>
      )}
      <ContactForm onSubmit={handleSubmit} />
    </>
  );
}