use-visibility-change
    TypeScript icon, indicating that this package has built-in type declarations

    0.5.0 • Public • Published

    use-visibility-change

    A custom React Hook that provides easy access to the visibilitychange event. Know how long it's been since a user has "seen" your app.

    npm version All Contributors

    Features

    🕐 Know how long the user has been away from your page.

    🕑 onHide called when the user changes tabs, closes the current tab, or minimizes the browser.

    🕒 onShow when the page is once again visible to the user (passing the lastSeenDate).

    🕓 Persists lastSeenDate to localStorage.

    use-visibility-change

    This hook was inspired by this piece on Web Platform News.

    Installation

    $ npm i use-visibility-change

    or

    $ yarn add use-visibility-change

    Usage

    Here is a basic setup.

    const result = useVisibilityChange(config);

    Parameters

    You pass a single config object with the following properties.

    Parameter Description
    onHide An optional callback function that is called upon closing or navigation away from the current tab, or minimizing the browser. You could use this callback to save the application state.
    onShow An optional callback function that is called with the same thing as the returned object when the view is restored. You could use this callback to restore the application state, or reset the user's experience if they have been gone for some time.
    storageKey A string that will be used as the key when persisting the last seen date. Default = "useSaveRestoreState.lastSeenDateUTC"
    shouldReturnResult A boolean that, if true, will cause useVisibilityChange to return a result object, otherwise it will return undefined and not update its internal state. This will help to decrease unnecessary re-renders. Default = false if onHide and onShow are specified, else true. You should normally never have to set this unless you have onHide and/or onShow callbacks and wish to have a result returned.

    Return

    This hook returns a result object with the following keys.

    Property Description
    lastSeenDate A Date object representing the date that the user was last "seen". Returns null if this is the first time the user visited your site with this browser.

    Example 1

    Here we have a simple case where we render how long it's been since the user has "seen" your app.

    const App = () => {
      const { lastSeenDate } = useVisibilityChange();
      return (
        <div>
          <p>Change tabs, navigate away, or close the tab. Then come back.</p>
          {lastSeenDate ? (
            <>
              <p className="hidden-for">
                This page was hidden for{' '}
                <em>{((new Date() - lastSeenDate) / 1000).toFixed(2)} secs</em>
              </p>
              <p>Last seen on: {lastSeenDate.toISOString()}</p>
            </>
          ) : (
            'Welcome new user!'
          )}
        </div>
      );
    };

    Live demo

    You can view/edit the sample code above on CodeSandbox.

    Edit demo app on CodeSandbox

    Example 2

    Here is another example that uses the onHide and onShow callbacks.

    use-visibility-change-2

    let savedTitle;
    
    const onHide = () => {
      savedTitle = document.title;
      document.title = '👋 Bye. See ya later!';
    };
    
    const onShow = () => {
      document.title = savedTitle;
    };
    
    const App = () => {
      useVisibilityChange({ onShow, onHide });
      return (
        <>
          <h1>useVisibilityChange demo.</h1>
          <p>Change tabs and notice the title.</p>
        </>
      );
    };

    Live demo

    You can view/edit the sample code above on CodeSandbox.

    Edit demo app on CodeSandbox

    License

    MIT Licensed

    Contributors

    Thanks goes to these wonderful people (emoji key):

    Donavon West
    Donavon West

    🤔 🚇 🚧 👀 💻 🎨

    This project follows the all-contributors specification. Contributions of any kind welcome!

    Keywords

    none

    Install

    npm i use-visibility-change

    DownloadsWeekly Downloads

    304

    Version

    0.5.0

    License

    MIT

    Unpacked Size

    31.6 kB

    Total Files

    13

    Last publish

    Collaborators

    • donavon