Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A React hook for determining whether or not a section of DOM still has the users attention. It's like clickAway logic on steroids
import { useState, useEffect, RefObject } from "react";
export default function useAttentionWithin(ref: RefObject<HTMLElement>) {
const [attentionWithin, setAttentionWithin] = useState(false);
function handleAttentionLeave({ target }: Event) {
const targetIsWithin = !!(
ref.current && ref.current.contains(target as Node)
useEffect(() => {
document.addEventListener("focusin", handleAttentionLeave);
document.addEventListener("mouseup", handleAttentionLeave);
return () => {
document.removeEventListener("focusin", handleAttentionLeave);
document.removeEventListener("mouseup", handleAttentionLeave);
}, []);
return attentionWithin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.