Skip to content

Instantly share code, notes, and snippets.

@humphd
Created November 19, 2020 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humphd/86008f4a7c743c7fcd6b74e640be4767 to your computer and use it in GitHub Desktop.
Save humphd/86008f4a7c743c7fcd6b74e640be4767 to your computer and use it in GitHub Desktop.
Custom hook for Page Lifecycle API
// Use it like this
import usePageLifecycle from './lib/use-page-lifecycle';
App() {
const isVisible = usePageLifecycle();
}
// Custom hook wrapped around https://github.com/GoogleChromeLabs/page-lifecycle
import { useState } from 'react';
import useEventListener from '@use-it/event-listener';
import lifecycle from 'page-lifecycle';
const usePageLifecycle = () => {
const stateIsVisible = (state) => state === 'active' || state === 'passive';
const [isVisible, setIsVisible] = useState(stateIsVisible(lifecycle.state));
const stateChangeHandler = (event) => {
// If the page is now visible and previously was not, update our internal state
if (stateIsVisible(event.newState) && !stateIsVisible(event.oldState)) {
console.log('Updating isVisible to true');
setIsVisible(true);
return;
}
// If the page is now not visible and previously was, update our internal state
if (!stateIsVisible(event.newState) && stateIsVisible(event.oldState)) {
console.log('Updating isVisible to false');
setIsVisible(false);
return;
}
};
useEventListener('statechange', stateChangeHandler, lifecycle);
return isVisible;
};
export default usePageLifecycle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment