/* see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon ```jsx const MyComponent = ({ children }) => { // will get fired if the page unloads while the component is mounted useUnloadBeacon({ url: 'https://api.my.site/route', payload: () => { return 'something' } }) return children } ``` */ import { useEffect } from 'react' export default function useUnloadBeacon({ url, payload = () => {} }) { const eventHandler = () => navigator.sendBeacon(url, payload()) useEffect(() => { window.addEventListener('unload', eventHandler, true) return () => { window.removeEventListener('unload', eventHandler, true) } }, []) }