Search code snippets, questions, articles... Chrome Extension

Custom hook to check window is visible

Returns whether the window is currently visible to the user. https://github.com/pancakeswap/pancake-frontend
import { useEffect, useState } from 'react'

const VISIBILITY_STATE_SUPPORTED = 'visibilityState' in document

function isWindowVisible() {
  if (!VISIBILITY_STATE_SUPPORTED) {
    return true
  }

  return document.visibilityState === 'visible'
}

/**
 * Returns whether the window is currently visible to the user.
 */
export default function useIsWindowVisible() {
  const [isVisible, setIsVisible] = useState(isWindowVisible())

  useEffect(() => {
    if (!VISIBILITY_STATE_SUPPORTED) return undefined

    const handleVisibilityChange = () => {
      setIsVisible(isWindowVisible())
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [setIsVisible])

  return isVisible
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Was this helpful?
0 Comments
Join Devsheet Ask a Question