DEV Community

Saurav Pandey
Saurav Pandey

Posted on • Originally published at sauravtbpandey.blogspot.com

Handling File Downloads and System Notifications in React Made Easy

Handling client-side file downloads and system notifications in React applications often requires writing repetitive DOM boilerplate, managing Blob memory leaks, and coordinating manual browser permission checks.

With the latest update to react-hook-lab, we are excited to announce two brand-new browser hooks that streamline these browser interactions: useDownload and useNotifications.


1. Declarative File Downloads with useDownload

Whether you need to generate a JSON export on the fly, trigger a text download, or fetch a file from a remote endpoint, useDownload handles the heavy lifting. It manages download state (idle, downloading, success, error), formats data correctly into Blobs, and automatically revokes object URLs to prevent memory leaks.

Quick Example: Exporting Data and Downloading Remote Files

import React from "react";
import { useDownload } from "react-hook-lab";

export function FileExportDemo() {
  const { download, status, error } = useDownload();

  const handleExportJson = async () => {
    const data = { user: "Jane Doe", role: "Developer", timestamp: Date.now() };
    await download(data, "user-data.json");
  };

  const handleDownloadRemote = async () => {
    await download("https://example.com/report.pdf", "monthly-report.pdf");
  };

  return (
    <div style={{ padding: "1rem", display: "flex", gap: "1rem" }}>
      <button onClick={handleExportJson} disabled={status === "downloading"}>
        {status === "downloading" ? "Exporting..." : "Export User JSON"}
      </button>

      <button onClick={handleDownloadRemote} disabled={status === "downloading"}>
        Download PDF Report
      </button>

      {error && <p style={{ color: "red" }}>Error: {error}</p>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. Desktop Notifications with useNotifications

Triggering browser-native OS notifications normally requires permission handling, checking browser support, and tracking active notification instances. useNotifications makes this seamless by managing permission status, re-checking state on window focus, and automatically closing active alerts on component unmount.

Quick Example: Requesting Permission and Sending Notifications

import React from "react";
import { useNotifications } from "react-hook-lab";

export function NotificationDemo() {
  const { sendNotification, requestPermission, permission, isSupported } = useNotifications({
    autoRequest: false,
  });

  const handleTriggerNotification = async () => {
    if (permission !== "granted") {
      const result = await requestPermission();
      if (result !== "granted") return;
    }

    sendNotification("Task Complete!", {
      body: "Your background export finished successfully.",
    });
  };

  if (!isSupported) {
    return <p>Desktop notifications are not supported in this browser.</p>;
  }

  return (
    <div>
      <p>Current Permission: <strong>{permission}</strong></p>
      <button onClick={handleTriggerNotification}>
        Trigger Notification
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Summary

  • useDownload: Supports downloading plain text, JSON objects, Blob instances, and remote/relative URLs with status tracking and automatic URL revocation.
  • useNotifications: Handles system notification permissions, auto-requests, desktop alert triggers, and auto-cleanup.

Resources & Links

Top comments (0)