Skip to content

useDownload

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useDownload

Downloads a Blob, plain string, JSON-serializable object, or remote URL. It dynamically handles fetching remote/relative URLs or generating text/JSON blobs on the fly.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, generating a JSON file from a plain object.

import { useDownload } from 'react-hook-lab';

function BasicExport() {
  const { download } = useDownload();

  const handleExport = () => {
    download({ user: "Alice", role: "Admin" }, "export.json");
  };

  return <button onClick={handleExport}>Download JSON</button>;
}

Common (Standard Usage)

Downloading a remote file (like an image or PDF) and tracking the loading state.

import { useDownload } from 'react-hook-lab';

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

  const downloadImage = () => {
    // Fetches the remote URL and converts it into a local blob download
    download("https://example.com/image.jpg", "cool-image.jpg");
  };

  return (
    <div>
      <button onClick={downloadImage} disabled={status === 'downloading'}>
        {status === 'downloading' ? 'Downloading...' : 'Download Image'}
      </button>
      {error && <p style={{color:'red'}}>{error}</p>}
    </div>
  );
}

Advanced (All Parameters)

An exhaustive example providing explicit MIME types and authenticated fetch options.

import { useDownload } from 'react-hook-lab';

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

  const downloadCSV = () => {
    // We provide a string, but tell the browser to treat it as a CSV file
    const csvContent = "name,age\nAlice,30\nBob,25";
    
    download(csvContent, "data.csv", {
      mimeType: "text/csv;charset=utf-8",
      // If we were passing a URL instead of a string, we could pass headers here:
      fetchOptions: {
        headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
      }
    });
  };

  return (
    <div>
      <button onClick={downloadCSV}>
        Export CSV Data {status === 'success' && '✅'}
      </button>
      {error && <p>Error: {error}</p>}
    </div>
  );
}

API Reference

Parameters

This hook takes absolutely zero initialization parameters.

Return Object

Returns UseDownloadReturn:

  • status (DownloadStatus): The current state of the download. Can be "idle" | "downloading" | "success" | "error".
  • error (string | null): The error message if the download fails (e.g., fetch failed, invalid filename).
  • download ((source: Blob | string | object, filename: string, options?: UseDownloadOptions) => Promise<boolean>): The asynchronous function to trigger the download.
    • source: The data to download. Can be a raw Blob, a string (which is treated as a URL if it starts with http or /, otherwise treated as plain text content), or a plain object (which is stringified to JSON).
    • filename: The desired filename (e.g., "data.json").
    • options.mimeType: Overrides the default MIME type for strings/objects.
    • options.fetchOptions: Passes a RequestInit configuration to the internal fetch call if the source is a URL.

Clone this wiki locally