Skip to content

useWindowEventListener

Adds an event listener to the window object.

The useWindowEventListener hook is helpful when you want attach event listener to the window object and run callbacks after the event is triggered.

The event listener attached will automatically be cleanuped once the component is unmounted.

This hook is exactly to useEventListenerOnRef, but with window object as target.

useWindowEventListener

Y Scroll : 0px

Scroll on the window to get the Y scroll position

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useWindowEventListener } from '@abhushanaj/react-hooks';
function App() {
const [yScroll, setYScroll] = React.useState<number>(0);
useWindowEventListener('scroll', () => {
setYScroll(window.scrollY);
});
return (
<div>
<p>Y Scroll : {yScroll}px</p>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
eventNamestringThe name of the event to listen to.N/A
callbackEventListenerOrEventListenerObjectThe event handler function to be executed when the event is triggered.N/A
optionsAddEventListenerOptions | boolean (optional)Additional options for the event listener.undefined

Note: The EventListenerOrEventListenerObject and AddEventListenerOptions are standard types defined by lib.dom.d.ts. You can refer the MDN spec for additional information.