A custom React Hook that executes a callback when a user is exiting your app- in both desktop and mobile browsers.
TL;DR: fires like a visibilitychange
to 'hidden'
, but with global usage compatibility of 99% (as opposed to the current 76%)
Web browsers can be weird about communicating the unloading of pages to developers. use-last-call attempts to abstract away that weirdness so a final invocation reliably occurs- whenever plausible. It listens, and responds, to the first in a series of browser events that indicate a user is transitioning away from a page (e.g. window close, refresh, history navigation, location change, tab switch, etc..). Some fun edge cases (read: weirdness):
- A mobile user receives a phone call mid-form-fill
- Security updates opt for "Restart Now" over "Remind me Later"
- Someone using Safari closes a tab . . . (」° ロ °)」
Try these (and your users' favorite non-traditional exits) in the demo app
npm i use-last-call
useLastCall(fn: (event: Event) => void): void;
Note: the callback fn
is passed the actual Event
that triggered execution
Send some analyticsData
at the end of a session
import { useLastCall } from "use-last-call";
function App() {
useLastCall(() => navigator.sendBeacon("/log", analyticsData));
...
}
Transparently save state without interrupting user
import { useState } from "react";
import { useLastCall } from "use-last-call";
function App() {
useLastCall(() => {
sessionStorage.setItem("formValues", JSON.stringify(formValues));
});
const [formValues, setFormValues] = useState<{
title: string;
description: string;
...
}>(() => {
const item = sessionStorage.getItem("formValues");
return item === null ? { title: "", description: "", ... } : JSON.parse(item);
});
return (
<div>
<input
type="text"
value={formValues.title}
onChange={(e) =>
setFormValues((prev) => ({ ...prev, title: e.target.value }))
}
/>
...
</div>
);
}