title: Detect click outside React component using hooks
body: <p>I am finding that I am reusing behaviour across an app that when a user clicks outside an element I can hide it. </p>
  
  <p>With the introduction of hooks is this something I could put in a hook and share across components to save me writing the same logic in every component?</p>
  
  <p>I have implemented it once in a component as follows.</p>
  
  <pre><code>const Dropdown = () =&gt; {
      const [isDropdownVisible, setIsDropdownVisible] = useState(false);   
      const wrapperRef = useRef&lt;HTMLDivElement&gt;(null);
  
      const handleHideDropdown = (event: KeyboardEvent) =&gt; {
          if (event.key === 'Escape') {
              setIsDropdownVisible(false);
          }
      };
  
      const handleClickOutside = (event: Event) =&gt; {
          if (
              wrapperRef.current &amp;&amp;
              !wrapperRef.current.contains(event.target as Node)
          ) {
              setIsDropdownVisible(false);
          }
      };
  
      useEffect(() =&gt; {
          document.addEventListener('keydown', handleHideDropdown, true);
          document.addEventListener('click', handleClickOutside, true);
          return () =&gt; {
              document.removeEventListener('keydown', handleHideDropdown, true);
              document.removeEventListener('click', handleClickOutside, true);
          };
      });
  
      return(
         &lt;DropdownWrapper ref={wrapperRef}&gt;
           &lt;p&gt;Dropdown&lt;/p&gt;
         &lt;/DropdownWrapper&gt;
      );
  }
  </code></pre>