Click Outside Magic: a new Custom Hook!

Click Outside Magic: a new Custom Hook!

Oct 16 2023

Performance is a crucial aspect of web application development, and ensuring a smooth user experience often involves detecting user interactions or element visibility. In this article, we'll introduce you to a custom React hook called useClickOutside. This hook simplifies the process of detecting clicks outside a specified element, a common requirement for implementing features like modals, dropdowns, or popovers. By leveraging useClickOutside, you can significantly improve the user experience in your React applications.


Introducing useClickOutside

The useClickOutside hook is designed to determine whether a user has clicked outside a specific element in a React application. It helps in scenarios where you want to close a modal, hide a dropdown, or dismiss a popover when the user clicks outside of the relevant component. The hook is straightforward and leverages the React useRef and useEffect functions.

Here's how the useClickOutside hook works:

1import { RefObject, useEffect } from 'react';
2
3export const useClickOutside = (
4  ref: RefObject<HTMLElement>,
5  handleOnClickOutside: (event: MouseEvent | TouchEvent) => void
6) => {
7  useEffect(() => {
8    const listener = (event: MouseEvent | TouchEvent) => {
9      if (!ref.current || ref.current.contains(event.target as Node)) {
10        return;
11      }
12      handleOnClickOutside(event);
13    };
14    document.addEventListener('mousedown', listener);
15    document.addEventListener('touchstart', listener);
16    return () => {
17      document.removeEventListener('mousedown', listener);
18      document.removeEventListener('touchstart', listener);
19    };
20  }, [ref, handleOnClickOutside]);
21}

How to Use useClickOutside

Let's look at an example of using the useClickOutside hook to close a modal when a user clicks outside of it:

1import React, { useRef } from 'react';
2import { useClickOutside } from './useClickOutside';
3
4function Modal() {
5  const modalRef = useRef();
6
7  // State to manage modal visibility
8  const [isOpen, setIsOpen] = useState(true);
9
10  // Function to close the modal
11  const closeModal = () => {
12    setIsOpen(false);
13  };
14
15  // Attach the click outside listener to the modal
16  useClickOutside(modalRef, closeModal);
17
18  return (
19    <div ref={modalRef} className={`modal ${isOpen ? 'open' : 'closed'}`}>
20      <div className="modal-content">
21        <p>Click outside to close this modal</p>
22      </div>
23    </div>
24  );
25}
26
27function App() {
28  return (
29    <div className="app">
30      <h1>React Click Outside Example</h1>
31      <Modal />
32    </div>
33  );
34}
35
36export default App;

In this example, the useClickOutside hook is applied to the Modal component, and it listens for clicks outside the modal's content. When a click occurs outside the modal, the closeModal function is called, which toggles the modal's visibility. This is just one of the many ways you can use the useClickOutside hook to enhance user interactions in your React applications.

In conclusion, the useClickOutside hook simplifies the process of handling click events outside a specific element, making your React application more user-friendly and performant. You can easily integrate this custom hook into your projects to provide a better user experience and optimize performance.

See more articles