Closing a menu when a user clicks outside of it with React Hooks

How do you improve the user experience of closing a menu? Don’t require the user to click an X just to get back to the content.

Closing a menu when a user clicks outside of it with React Hooks
Photo by lucas law / Unsplash

One of the best user experience additions to a menu, is closing that menu when a user clicks outside of it. When a drop down opens, and the one way to close it is selecting another drop down or clicking a x, it drives me nuts. The thing that I want to do is click outside of it, as I tap off that menu.

Here is a example of how to use a useRef and useEffect hook to handle this. The useEffect runs every time the component renders. It checks if the click event is part of the current reference, and if it the target of the event is contained within. If it fails this check, it closes the menu by setting showMenu to false.

const menuRef = useRef(null);

  // Hides menu on clicking outside of it
  useEffect(() => {
    function handleClickOutside(event) {
      if (menuRef.current && !menuRef.current.contains( {

    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
  }, [menuRef]);

Other things that you can do for menus that focus trap, is to allow escape the close the menu. This improves the accessibility for keyboard users, but it also allows the user to use the built in control for this. After all it’s called the “Escape” key.