This hook lets you know when your mouse pointer is active on a particular element. It needs a ref of the element in question to work with. It can also take an onChange callback which it calls everytime the active state changes. The onChange function recieves the current active state of the element as a boolean value.

💡 Implementation
Pretty
Copy
function useActive({ onChange, refEl }) {
const [value, setValue] = useState(false);
const handleMouseDown = () => {
setValue(true);
onChange(true);
};
const handleMouseUp = () => {
setValue(false);
onChange(false);
};
useEffect(() => {
if (refEl && refEl.current) {
refEl.current.addEventListener("mousedown", handleMouseDown);
refEl.current.addEventListener("mouseup", handleMouseUp);
}
return () => {
if (refEl && refEl.current) {
refEl.current.removeEventListener("mousedown", handleMouseDown);
refEl.current.removeEventListener("mouseup", handleMouseUp);
}
};
}, []);
return value;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
🚀 Usage
Pretty
Copy
function Demo() {
const inputEl = useRef(null);
const activeValue = useActive({ refEl: inputEl });
return (
<>
<input ref={inputEl} type="text" />
<div>{activeValue ? "Active" : "Nop"}</div>
</>
);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
âš¡Preview
Nop
🚨 console
Contributors