Created
November 19, 2020 01:29
-
-
Save humphd/86008f4a7c743c7fcd6b74e640be4767 to your computer and use it in GitHub Desktop.
Custom hook for Page Lifecycle API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use it like this | |
import usePageLifecycle from './lib/use-page-lifecycle'; | |
App() { | |
const isVisible = usePageLifecycle(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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