UNPKG

@gitgw/use-before-leave

Version:

React Hook to execute a function when the mouse leaves the page. Useful to show a popup or for analytics.

21 lines (17 loc) 449 B
import { useEffect } from "react"; export const useBeforeLeave = (onBefore) => { const handleMouseLeave = (event) => { if (event.clientY <= 0) { onBefore(); } }; useEffect(() => { document.addEventListener("mouseleave", handleMouseLeave); return () => { document.removeEventListener("mouseleave", handleMouseLeave); }; }, []); if (typeof onBefore !== "function") { return; } };