Code Monkey home page Code Monkey logo

use-last-call's Introduction

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

use-last-call's People

Contributors

julesferreira avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

terranc

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.