useWindowsFocus
React Element Hook that tracks window focus with window.onfocus and window.onblur events
useWindowsFocus reactively tracks whether the browser window currently has focus by listening to window.onfocus and window.onblur events. It returns a boolean that is true when the window is focused and false when it is not. You can optionally provide a default value for the initial state.
When to Use
- Pausing real-time updates (e.g., WebSocket messages or polling) when the user switches to another application
- Showing visual indicators like “you are away” or dimming the UI when the window loses focus
- Resuming or refreshing data when the user returns to the application window
Notes
- SSR-safe: Returns the provided
defaultValue(ortrue) during server-side rendering sincewindowis not available. - Cleanup: Event listeners are removed automatically when the component unmounts.
- See also
useDocumentVisibilityfor tracking tab visibility (which also covers minimized windows), anduseFocusfor tracking focus on individual elements.
Usage
Live Editor
function Demo() { const focus = useWindowsFocus(); return ( <div> <p> {focus ? "💡 Click somewhere outside of the document to unfocus." : "ℹ Tab is unfocused"} </p> </div> ); };
Result
API
useWindowsFocus
Returns
boolean: whether window focus
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| defauleValue | defauleValue | boolean | undefined | - |