Skip to content

useDocumentEventListener

Adds an event listener to the document object.

The useDocumentEventListener hook is helpful when you want attach event listener to the document 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 document object as target.

useDocumentEventListener

Click anywhere on document to trigger an event (only once)

Usage

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

./src/App.tsx
import { useDocumentEventListener } from '@abhushanaj/react-hooks';
function App() {
useDocumentEventListener('click', () => {
alert('Click event triggered');
});
return <p>Click anywhere on document to trigger the event.</p>;
}
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.