Build a useOnClickOutside Hook

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write a custom hook and export it by name: useOnClickOutside(ref, handler), where ref is a ref attached to an element. Whenever the user presses or clicks anywhere on the page outside that element, call handler with the event (listen on the document for mousedown, pointerdown or click). Presses on the element itself or anything inside it don't count, and when ref.current is empty (null) nothing happens. If the component re-renders with a new handler, call the newest one. Stop listening when the component unmounts. The default export App is a panel that closes when you click outside it; the checks test useOnClickOutside itself.

Your code must pass

  • Calls the handler for a click outside the element
  • Ignores clicks inside the element and its children
  • Calls the newest handler
  • Stops listening when unmounted