30% offEnding soon
useVibrateLoading saved progress…

useVibrate

The Vibration API lets a page request short pulses of tactile feedback from supported devices. Implement a React hook that detects navigator.vibrate after mount and exposes stable functions for starting or cancelling a pattern. The functions must remain safe when the API is absent or changes during the hook's lifetime.

Signature

type VibratePattern = number | number[];

function useVibrate(): {
  isSupported: boolean;
  vibrate: (pattern: VibratePattern) => boolean;
  cancel: () => boolean;
};

Examples

const { isSupported, vibrate } = useVibrate();

// Call from a user interaction such as a click.
vibrate(120); // forwards 120 to navigator.vibrate
const { vibrate, cancel } = useVibrate();

vibrate([80, 40, 160]); // vibrate, pause, vibrate
cancel();               // forwards 0 to navigator.vibrate

Notes

  • Start isSupported at false, then detect whether navigator.vibrate is a function in an effect. This keeps the first render safe outside a browser.
  • Read navigator.vibrate again whenever vibrate or cancel is called. If it is missing, return false without throwing.
  • Pass a number or array to the native method unchanged. Return the boolean value of the native result.
  • cancel must call navigator.vibrate(0) and return the boolean value of that call.
  • Keep both callback identities stable across rerenders. Do not vibrate on mount, validate patterns, schedule retries, or track whether hardware is currently moving.

FAQ

Does a true return value guarantee that the device physically vibrated?
No. It means the browser accepted the request; hardware, system settings, or browser policy can still prevent physical feedback.
How do you stop a vibration pattern?
Call navigator.vibrate with 0. The platform also treats an empty array or an all-zero pattern as cancellation.
Why should vibrate be called from a click or key handler?
Browsers require sticky user activation before allowing vibration, so an interaction must have occurred on the page.