Hook
usePageVisibility
usePageVisibility exposes the browser visibility boundary that mobile applications can use to pause work, persist local state, and refresh data after returning to the foreground.
Preview
Current page lifecycle
Visibility
Visible
Was discarded
Switch tabs or minimize the browser to change the visibility state.
Installation
pnpm dlx shadcn@latest add https://pwaui.com/r/use-page-visibility.jsonUsage
"use client"
import * as React from "react"import { usePageVisibility } from "@/hooks/use-page-visibility"
export function RefreshOnReturn() { const { isVisible } = usePageVisibility()
React.useEffect(() => { if (isVisible) void refreshData() }, [isVisible])
return null}Returns
visibilityState- unknown during server rendering, then the document visibility state.
isVisible- null while unknown, otherwise whether the document is visible.
wasDiscarded- Whether the browser restored this load after discarding the previous page.
Behavior notes
- Visibility changes are a better mobile session boundary than relying on unload.
- Pause polling and visual work while hidden, and revalidate data when the page returns.
- Keep persistence work small because the browser may suspend or discard the page shortly after it becomes hidden.