use-last-call
TypeScript icon, indicating that this package has built-in type declarations

0.2.1 • Public • Published

A custom React Hook that executes a callback when a user is exiting your app- in both desktop and mobile browsers.

Overview

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

Install

npm i use-last-call

Use

useLastCall(fn: (event: Event) => void): void;

Note: the callback fn is passed the actual Event that triggered execution

Example: send analytics

Send some analyticsData at the end of a session

import { useLastCall } from "use-last-call";

function App() {
  useLastCall(() => navigator.sendBeacon("/log", analyticsData));
  ...
}

Example: save state

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>
  );
}

See also

Package Sidebar

Install

npm i use-last-call

Weekly Downloads

1

Version

0.2.1

License

MIT

Unpacked Size

13.6 kB

Total Files

13

Last publish

Collaborators

  • julesferreira