Skip to content

Instantly share code, notes, and snippets.

@tmarshall
Last active June 18, 2022 02:39
Show Gist options
  • Save tmarshall/b5433a2c2acd5dbfc592bbc4dd4c519c to your computer and use it in GitHub Desktop.
Save tmarshall/b5433a2c2acd5dbfc592bbc4dd4c519c to your computer and use it in GitHub Desktop.
React hook for unload beacons
/*
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