💡 3. useClick
import { useRef, useEffect } from "react";
const useClick = (onClick) => {
const ref = useRef();
useEffect(() => {
const element = ref.current;
if (typeof onClick !== "function") {
return;
}
if (element) {
element.addEventListener("click", onClick);
}
return () => {
if (element) {
element.removeEventListener("click", onClick);
}
};
}, [onClick]);
return ref;
};
export default useClick;
💡 4. useConfirm
const useConfirm = (message = "", onConfirm, onReject) => {
if (!onConfirm && typeof callback !== "function") {
return;
}
if (!onReject && typeof onReject !== "function") {
return;
}
const confirmAction = () => {
if (window.confirm(message)) {
onConfirm();
} else {
onReject();
}
};
return confirmAction;
};
export default useConfirm;
💡 5. useBeforeLeave
import { useEffect } from "react";
const useBeforeLeave = (onBefore, event = "mouseleave") => {
const handle = () => {
onBefore();
};
useEffect(() => {
if (typeof event !== "string") {
return;
}
if (typeof onBefore !== "function") {
return;
}
document.addEventListener(event, handle);
return () => document.removeEventListener(event, handle);
});
};
export default useBeforeLeave;
💡 6. useEventRef
import { useRef, useEffect } from "react";
const useEventRef = (fucntion, event) => {
const ref = useRef();
useEffect(() => {
const element = ref.current;
if (typeof fucntion !== "function") {
return;
}
if (element) {
element.addEventListener(event, fucntion);
}
return () => {
if (element) {
element.removeEventListener(event, fucntion);
}
};
}, [fucntion, event]);
return ref;
};
export default useEventRef;
💡 7. useScroll
import { useState, useEffect } from "react";
const useScroll = () => {
const [state, setState] = useState({
x: 0,
y: 0,
});
const onScroll = () => {
setState({ x: window.scrollX, y: window.scrollY });
};
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
};
}, []);
return state;
};
export default useScroll;
💡 8. useConfirm
const useConfirm = (message = "", onConfirm, onReject) => {
if (!onConfirm && typeof callback !== "function") {
return;
}
if (!onReject && typeof onReject !== "function") {
return;
}
const confirmAction = () => {
if (window.confirm(message)) {
onConfirm();
} else {
onReject();
}
};
return confirmAction;
};
export default useConfirm;