# 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

```ts
import { useWindowFocus } from '@vincent.ri/react-tils'
// or only this hook
import { useWindowFocus } from '@vincent.ri/react-tils/useWindowFocus'
```

## Usage

```ts
const focused = useWindowFocus()
useEffect(() => {
  if (focused) markAsRead(conversationId)
}, [focused, conversationId])
```

## 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

```ts
function useWindowFocus(serverValue?: boolean): boolean
```

| Parameter | Description |
| --- | --- |
| `serverValue` | Value on the server and during hydration. Default `true`. |

## Browser support

Works in all modern browsers.

---

113 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useWindowFocus.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useWindowFocus/
Previous: [useDocumentVisibility](https://vincentri.github.io/react-tils/hooks/useDocumentVisibility.md)
Next: [useIdle](https://vincentri.github.io/react-tils/hooks/useIdle.md)
