javascript 30 lines · 7 steps

A click-outside hook in React

A custom hook that fires a callback whenever the user clicks or taps outside a referenced element.

Explained by highlit
1import { useEffect, useRef } from 'react';
2 
3export function useOnClickOutside(handler) {
4 const ref = useRef(null);
5 const savedHandler = useRef(handler);
6 
7 useEffect(() => {
8 savedHandler.current = handler;
9 }, [handler]);
10 
11 useEffect(() => {
12 const listener = (event) => {
13 const el = ref.current;
14 if (!el || el.contains(event.target)) {
15 return;
16 }
17 savedHandler.current(event);
18 };
19 
20 document.addEventListener('mousedown', listener);
21 document.addEventListener('touchstart', listener);
22 
23 return () => {
24 document.removeEventListener('mousedown', listener);
25 document.removeEventListener('touchstart', listener);
26 };
27 }, []);
28 
29 return ref;
30}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing a callback in a ref lets an effect stay mounted while always calling the latest version.
  2. 2Returning a cleanup function from useEffect removes global listeners so they don't leak across unmounts.
  3. 3Comparing event.target against a ref's DOM node is the standard way to detect clicks outside an element.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A click-outside hook in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code