바깥 클릭 감지를 useEffect 없이 ref callback 하나로 만든다.
React 19 이상에서만 된다.1
function useClickOutside(handler) {
const handlerRef = useRef(handler)
handlerRef.current = handler // stale closure 방지
return useCallback((node) => {
const handleClick = (e) => {
if (!node.contains(e.target)) handlerRef.current()
}
document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [])
}
// 사용
function Modal({ onClose }) {
const ref = useClickOutside(onClose)
return <div ref={ref}>...</div>
}
Footnotes
-
React v19 — Cleanup functions for refs: “When the component unmounts, React will call the cleanup function returned from the
refcallback.” / “Previously, React would callreffunctions withnullwhen unmounting the component. If yourrefreturns a cleanup function, React will now skip this step.” ↩