DEV Community

Discussion on: useDumbHooks

Collapse
 
simoroshka profile image
Anna Simoroshka

I wrote one dumb hook (extracted from the code, actually), useClickAway, which detects a click outside of the element (so I could hide the dropdown menu, for example). It just was nicer to have it separated instead of that code being copypasted around in different components.

Collapse
 
stereobooster profile image
stereobooster

Nice. Do you have it as open source repo or a gist or a codesandbox?

Collapse
 
simoroshka profile image
Anna Simoroshka • Edited

Well, here it is.

import { useEffect } from 'react';

export default function useClickAway(onClickAway, ref) {
  useEffect(() => {
    document.addEventListener('mousedown', handleClick);
    return () => {
      document.removeEventListener('mousedown', handleClick);
    };
  }, []);

  function handleClick(event) {
    if (ref.current && !ref.current.contains(event.target)) onClickAway();
  }
}

Thread Thread
 
simoroshka profile image
Anna Simoroshka

This is what I did before in the component and how it's now:

componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  setWrapperRef = node => {
    this.wrapperRef = node;
  };

  handleClickOutside = event => {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      this.props.onClickAway();
    }
  };

vs

const wrapperRef = useRef();
useClickAway(props.onClickAway, wrapperRef);