React useClickOutside hook

React, Hooks, Effect, Event · Nov 16, 2020

Handles the event of clicking outside of the wrapped component.

  • Create a custom hook that takes a ref and a callback to handle the click event.
  • Use the useEffect() hook to append and clean up the click event.
  • Use the useRef() hook to create a ref for your click component and pass it to the useClickOutside hook.
const useClickOutside = (ref, callback) => {
  const handleClick = e => {
    if (ref.current && !ref.current.contains( {
  React.useEffect(() => {
    document.addEventListener('click', handleClick);
    return () => {
      document.removeEventListener('click', handleClick);
const ClickBox = ({ onClickOutside }) => {
  const clickRef = React.useRef();
  useClickOutside(clickRef, onClickOutside);
  return (
        border: '2px dashed orangered',
        height: 200,
        width: 400,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      <p>Click out of this element</p>

  <ClickBox onClickOutside={() => alert('click outside')} />

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • React useClickInside hook

    Handles the event of clicking inside the wrapped component.

    React, Hooks · Nov 16, 2020

  • React useHover hook

    Handles the event of hovering over the wrapped component.

    React, Hooks · Oct 5, 2021

  • React usePortal hook

    Creates a portal, allowing rendering of children outside the parent component.

    React, Hooks · Jan 5, 2022