blakeblackshear.frigate/web/src/hooks/useClickOutside.jsx
Bernt Christian Egeland 00ff76a0b9
Events performance (#1645)
* rearrange event route and splitted into several components

* useIntersectionObserver

* re-arrange

* searchstring improvement

* added xs tailwind breakpoint

* useOuterClick hook

* cleaned up

* removed some video controls for mobile devices

* lint

* moved hooks to global folder

* moved buttons for small devices

* added button groups

Co-authored-by: Bernt Christian Egeland <cbegelan@gmail.com>
2021-09-03 07:11:23 -05:00

23 lines
836 B
JavaScript

import { useEffect, useRef } from 'preact/hooks';
// https://stackoverflow.com/a/54292872/2693528
export const useClickOutside = (callback) => {
const callbackRef = useRef(); // initialize mutable ref, which stores callback
const innerRef = useRef(); // returned to client, who marks "border" element
// update cb on each render, so second useEffect has access to current value
useEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
function handleClick(e) {
if (innerRef.current && callbackRef.current && !innerRef.current.contains(e.target)) callbackRef.current(e);
}
}, []);
return innerRef; // convenience for client (doesn't need to init ref himself)
};