FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Use Event Listener

20mins

Implement a hook useEventListener(target, event, handler) that allows subscribing to browser events.

The hook should:

  • Accept a target (like window, document, or an element), an event name, and a callback function.
  • Attach the event listener to the target when the hook is used.
  • Automatically clean up the listener when no longer needed or when the target/event changes.
  • Support dynamically changing targets and handlers.

Example

const handler = () => console.log('Clicked!'); useEventListener(document, 'click', handler); // When the user clicks anywhere in the document, 'Clicked!' is logged

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests