Last active
June 18, 2022 02:39
-
-
Save tmarshall/b5433a2c2acd5dbfc592bbc4dd4c519c to your computer and use it in GitHub Desktop.
React hook for unload beacons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) | |
} | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment