Docs
Visibility Change

Visibility Change

Track document visibility and respond to changes

About

The useVisibilityChange hook tracks the visibility state of a document or webpage. It detects when the document is visible or hidden, performing actions based on that information. The hook returns a boolean value indicating the document’s visibility, allowing components to react and update their behavior accordingly.

Return Values

NameTypeDescription
documentVisiblebooleantrue if the document is currently visible, false otherwise.

Installation

Run the following command:

npx scriptkavi-hooks@latest add visibility-change

Usage

import { useVisibilityChange } from "@/hooks/visibility-change"
import * as React from "react"
 
export default function App() {
  const documentVisible = useVisibilityChange()
  const [tabAwayCount, setTabAwayCount] = React.useState(0)
 
  React.useEffect(() => {
    if (documentVisible === false) {
      setTabAwayCount((c) => c + 1)
    }
  }, [documentVisible])
 
  return (
    <section>
      <h1>useVisibilityChange</h1>
      <div>Tab Away Count: {tabAwayCount}</div>
    </section>
  )
}