FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

useClickOutside

20mins

Implement a hook useClickOutside(ref, callback) that detects clicks outside of a specified element.

The hook should:

  • Accept a reference to an HTML element and a callback function.
  • Call the callback when a click happens outside the referenced element.
  • Ensure the event listener is properly cleaned up when the component unmounts.

Example

const ref = useRef(null); useClickOutside(ref, () => { console.log("Clicked outside!"); });

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests