import { useEffect } from 'react' ; import { useRefresh } from '../sideEffect' ; import useIsAutomaticRefreshEnabled from './useIsAutomaticRefreshEnabled' ; param { number } delay const useRefreshWhenVisible = ( delay = 1000 * 60 * 5 ) => { const refresh = useRefresh ( ) ; const automaticRefreshEnabled = useIsAutomaticRefreshEnabled ( ) ; useEffect ( ( ) => { if ( typeof document === 'undefined' ) return ; let lastHiddenTime ; const handleVisibilityChange = ( ) => { if ( ! automaticRefreshEnabled ) { return ; } if ( document . hidden ) { lastHiddenTime = Date . now ( ) ; } else { if ( Date . now ( ) - lastHiddenTime > delay ) { refresh ( ) ; } lastHiddenTime = null ; } } ; document . addEventListener ( 'visibilitychange' , handleVisibilityChange , { capture : true , } ) ; return ( ) => document . removeEventListener ( 'visibilitychange' , handleVisibilityChange , { capture : true } ) ; } , [ automaticRefreshEnabled , delay , refresh ] ) ; } ; export default useRefreshWhenVisible ;