All hooks / Page, device, and user
useWindowFocus
Whether the browser window has focus, updated on focus and blur.
Renders serverValue on the server and during hydration, then switches to document.hasFocus() with no hydration mismatch.
Import
import { useWindowFocus } from '@vincent.ri/react-tils'
// or only this hook
import { useWindowFocus } from '@vincent.ri/react-tils/useWindowFocus'Usage
const focused = useWindowFocus()
useEffect(() => {
if (focused) markAsRead(conversationId)
}, [focused, conversationId])Live demo
Switch tabs or windows and come back.
When to use it
The page is visible but the user is in another window, e.g. pause a game, mark messages as read only while focused, or refetch on return.
When not to
You mean "the tab is hidden"; use useDocumentVisibility (a visible page can be unfocused, e.g. side by side with another window). For focus inside the page (which input is active), use focus/blur handlers or CSS :focus-within.
API
function useWindowFocus(serverValue?: boolean): boolean| Parameter | Description |
|---|---|
serverValue | Value on the server and during hydration. Default true. |
Browser support
Uses only long-established browser features, so it works wherever React does.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).