Skip to content

Commit c17f888

Browse files
convert useHover hook to TS
1 parent c2f3a9e commit c17f888

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/pages/useHover.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: useHover
44
date: "2018-10-30"
55
gist: https://gist.github.com/gragland/cfc4089e2f5d98dde5033adc44da53f8
66
sandbox: https://codesandbox.io/s/01w2zmj010
7+
isMultilingual: true
78
links:
89
- url: https://gist.github.com/gragland/a32d08580b7e0604ff02cb069826ca2f
910
name: useHover with callback ref
@@ -51,3 +52,42 @@ function useHover() {
5152
return [ref, value];
5253
}
5354
```
55+
56+
```typescript
57+
// Usage
58+
function App() {
59+
const [hoverRef, isHovered] = useHover<HTMLDivElement>();
60+
61+
return <div ref={hoverRef}>{isHovered ? "😁" : "☹️"}</div>;
62+
}
63+
64+
// Hook
65+
// T - could be any type of HTML element like: HTMLDivElement, HTMLParagraphElement and etc.
66+
// hook returns tuple(array) with type [any, boolean]
67+
function useHover<T>(): [any, boolean] {
68+
const [value, setValue] = useState<boolean>(false);
69+
70+
const ref: any = useRef<T | null>(null);
71+
72+
const handleMouseOver = (): void => setValue(true);
73+
const handleMouseOut = (): void => setValue(false);
74+
75+
useEffect(
76+
() => {
77+
const node: any = ref.current;
78+
if (node) {
79+
node.addEventListener("mouseover", handleMouseOver);
80+
node.addEventListener("mouseout", handleMouseOut);
81+
82+
return () => {
83+
node.removeEventListener("mouseover", handleMouseOver);
84+
node.removeEventListener("mouseout", handleMouseOut);
85+
};
86+
}
87+
},
88+
[ref.current] // Recall only if ref changes
89+
);
90+
91+
return [ref, value];
92+
}
93+
```

0 commit comments

Comments
 (0)