Declarative, nested, stateful, isomorphic page visibility React component
Declarative, nested, stateful, isomorphic page visibility for React
Are you polling your Backend on an interval basis? Are you running animations? What do you do if your tab is no longer visible?
See more classic use-cases in MDN Page Visibility API.
Well now you can react (Pun intended) to your app being in the background and invisible by conserving bandwidth and GPU calculations with ease. Introduction React Page Visibility:
Because React is cool. 'Nuff said.
But really, why not use a helper function? Because you will then need to
addEventListenerand
removeEventListenerin your component lifecycle and that gets tedious.
Also, every time you use it you will need to check if your user's browser supports it and that gets tedious too.
Instead with
react-page-visibilityeverything is taken care of for you.
$ npm install --save react-page-visibility
A rotating carousel component that will be passed down a prop of whether to rotate the images or not based on whether page is visible.
usePageVisibilityhook
import React from 'react'; import { usePageVisibility } from 'react-page-visibility';const AppContainer = () => { const isVisible = usePageVisibility()
return <rotatingcarousel rotate="{isVisible}"></rotatingcarousel>
}
onChangecallback
import React from 'react'; import PageVisibility from 'react-page-visibility';class AppContainer extends React.Component { state = { rotate: true };
handleVisibilityChange = isVisible => { this.setState({ rotate: !isVisible }); } render() { return ( <pagevisibility onchange="{this.handleVisibilityChange}"> <rotatingcarousel rotate="{this.state.rotate}"></rotatingcarousel> </pagevisibility> ); }
}
childrenas function callback
import React from 'react'; import PageVisibility from 'react-page-visibility';const AppContainer = () => { return ( { isVisible => } ); }
react-page-visibilityis an higher order component, you can pass to it an
onChangefunction:
onChange(handler)
Where
handleris the callback to run when the
visibilityStateof the document changes:
Function handler( isVisible, visibilityState)
isVisibleis a Boolean indicating whether document is considered visible to the user or not.
visibilityStateis a String and can be one of
visible,
hidden,
prerender,
unloaded(if your browser supports those)
Notice: previous versions had different arguments in the
handler
Or you can use function as children pattern, where
childrenis the callback to run when the
visibilityStateof the document changes.
Function children( isVisible, visibilityState)
See MDN Page Visibility API Properties overview
MIT © Gilad Peleg