30% offEnding soon
useWebShareLoading saved progress…

useWebShare

The Web Share API opens the device's native share sheet for text, links, and supported files. Implement a React hook that detects navigator.share, optionally checks data with navigator.canShare, and exposes one stable method for starting the operation. Your hook must remain safe when rendered outside a supporting browser.

Signature

type ShareData = {
  title?: string;
  text?: string;
  url?: string;
  files?: File[];
};

function useWebShare(): {
  isSupported: boolean;
  canShare: (data: ShareData) => boolean;
  share: (data: ShareData) => Promise<void>;
};

Examples

const { isSupported, canShare, share } = useWebShare();

isSupported; // true when navigator.share is a function
canShare({ text: 'Read this' }); // navigator.canShare's boolean, when available

// Call from a click handler to preserve transient user activation.
await share({ title: 'UIReady', url: 'https://uiready.dev' });
// navigator.share exists, but navigator.canShare does not:
canShare({ text: 'Hello' }); // true; the native call performs final validation

// navigator.canShare returns false:
await share({ files: [] }); // rejects without calling navigator.share

Notes

  • Safe first render — initialize isSupported without reading navigator, then reconcile it in an effect after mount.
  • Call-time APIscanShare and share must read navigator when invoked while keeping stable function identities across rerenders.
  • Native errors — preserve rejections from navigator.share, including the user's AbortError cancellation.
  • Browser requirements — Web Share needs a secure context, an allowed web-share Permissions Policy, and transient activation. Call share directly from a click or similar user action.
  • Out of scope — do not add clipboard fallbacks, Web Share Target support, success/error state, file special cases, data mutation, or workarounds for user activation.

FAQ

Why should share be called from a click handler?
Browsers require transient user activation for navigator.share(), so call the hook's share method directly from a user action such as a button click.
What happens when navigator.canShare is missing?
If navigator.share exists, this hook reports the data as potentially shareable and lets the native share call perform the final validation.