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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing a callback in a ref lets an effect stay mounted while always calling the latest version.
- 2Returning a cleanup function from useEffect removes global listeners so they don't leak across unmounts.
- 3Comparing event.target against a ref's DOM node is the standard way to detect clicks outside an element.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-click-outside-hook-in-react-explained-javascript-25b7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.