-
Notifications
You must be signed in to change notification settings - Fork 0
useDownload
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
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.
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>;
}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>
);
}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>
);
}This hook takes absolutely zero initialization parameters.
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 rawBlob, astring(which is treated as a URL if it starts withhttpor/, otherwise treated as plain text content), or a plainobject(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 aRequestInitconfiguration to the internalfetchcall if the source is a URL.
-
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM