visibilitychange 는 탭 전환·최소화·앱 전환처럼 보임 상태가 바뀔 때 document 에서 발생한다.1

const isVisible = document.visibilityState === 'visible'
const isHidden = document.visibilityState === 'hidden'

document.addEventListener('visibilitychange', onChange)

시스템이 잠들면 visibilitychange 가 안 올 때가 있다 — hidden 상태일 때만 입력으로 복귀를 잡는다.2

if (document.visibilityState === 'hidden') {
  document.addEventListener('mouseenter', setVisible)
  document.addEventListener('keydown', setVisible)
}

const [isVisible, setIsVisible] = useState(true)

useEffect(() => {
  const onChange = () => {
    const newState = document.visibilityState !== 'hidden'

    if (newState !== isVisible) {
      setIsVisible(newState)
    }
  }

  // addEventListener

  return () => {
    // removeEventListener
  }
}, [isVisible])

Footnotes

  1. Document: visibilitychange event - MDN: “The visibilitychange event is fired at the document when its visibility status changes — for example, when the user switches browser tabs, navigates to a new page, minimizes or closes the browser, or on mobile, switches to a different app.” ↩

  2. use-visibility-state/src/index.tsx: “When the system goes to sleep, sometimes the visibilitychange event is not fired. In that case, we can use mouseenter or keydown to detect when the window is focused.” ↩

#490