Skip to content

Commit

Permalink
Add the useHover hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Goosens committed Apr 4, 2024
1 parent 80c3b22 commit 0339b88
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/soft-sloths-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codedazur/react-essentials": minor
---

Add the useHover hook
32 changes: 32 additions & 0 deletions packages/react-essentials/hooks/useHover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { RefObject, useEffect, useState } from "react";

/**
* Determine if the element is hovered by the user.
*
* @param elementRef
* @returns boolean
*/
export function useHover<T extends HTMLElement = HTMLElement>(
elementRef: RefObject<T>,
): boolean {
const [isHovered, setIsHovered] = useState(false);

const mouseEnterHandler = () => setIsHovered(true);
const mouseLeaveHandler = () => setIsHovered(false);

useEffect(() => {
const element = elementRef.current;

if (element) {
element.addEventListener("mouseenter", mouseEnterHandler);
element.addEventListener("mouseleave", mouseLeaveHandler);

return () => {
element.removeEventListener("mouseenter", mouseEnterHandler);
element.removeEventListener("mouseleave", mouseLeaveHandler);
};
}
}, [elementRef]);

return isHovered;
}

0 comments on commit 0339b88

Please sign in to comment.