Skip to main content

useShare

The useShare hook wraps the Web Share API, which opens the native share sheet on phones, tablets, and some desktop browsers. Closing the sheet without sharing is not treated as an error.

Usage​

Installation​

import { useShare } from "hookstorm";

Parameters​

This hook does not take any parameters.

Return Values​

  • isSupported — true if the browser can share.
  • isSharing — true while the share sheet is open.
  • error — The last error, or null.
  • share(data) — Opens the share sheet for a ShareData object (title, text, url, files). Returns a promise that resolves to true if the share was completed.

Example Usage​

import { ReactElement } from "react";
import { useShare } from "hookstorm";

export default function ShareButton(): ReactElement {
const { isSupported, isSharing, error, share } = useShare();

if (!isSupported) return <p>Sharing is not supported on this device.</p>;

return (
<div>
<button
disabled={isSharing}
onClick={() => share({ title: "Hookstorm", url: window.location.href })}
>
Share this page
</button>
{error && <p>Could not share: {error.message}</p>}
</div>
);
}

Notes​

  • Browsers only allow sharing from a user gesture such as a click, so call share from an event handler.
  • Render a fallback (for example a copy-link button using useCopyToClipboard) when isSupported is false.
  • Requires a secure context (https:// or localhost).