useEvent
Adds a native event listener of type to a target.
Executes listener when the event of type type is dispatched.
- @param
target- The target to add the event listener to. Values of typestringare used instead of their respective global objects to ensure compatibility with server-side rendering. - @param
type- The event type to listen for, the available options are derived from thetarget. - @param
listener- The event listener to be called when the event is dispatched. - @param
options- Configurable options - @returns void
Example
const [width, setWidth] = useState<number | null>(null)
useEvent('window', 'resize', (event) => {
if (event.defaultPrevented) return
setWidth(window.innerWidth)
}, { passive: true })