useWindowFocus
Track whether the browser window or tab is currently focused.
👨💻
Active Now
Viewing this Page
Last seen active at6:44:41 PM
Try switching to another tab and come back!
Usage
import { useWindowFocus } from 'usehooks-ts'
export default function App() {
const isFocused = useWindowFocus()
return (
<div>
<p>Window is focused: {isFocused ? '🟢 Yes' : '🌙 No'}</p>
</div>
)
}API
const isFocused = useWindowFocus()Return Values
| Name | Type | Description |
|---|---|---|
isFocused | boolean | true if window has focus |
Hook
import { useEffect, useState } from 'react'
export function useWindowFocus(): boolean {
const [focused, setFocused] = useState(
typeof window !== 'undefined' ? document.hasFocus() : true,
)
useEffect(() => {
const handleFocus = () => setFocused(true)
const handleBlur = () => setFocused(false)
window.addEventListener('focus', handleFocus)
window.addEventListener('blur', handleBlur)
return () => {
window.removeEventListener('focus', handleFocus)
window.removeEventListener('blur', handleBlur)
}
}, [])
return focused
}