Skip to content

Instantly share code, notes, and snippets.

@jackdh
Created June 1, 2020 12:30
Show Gist options
  • Save jackdh/102ff28c3cf64d3758273f3984fd20ec to your computer and use it in GitHub Desktop.
Save jackdh/102ff28c3cf64d3758273f3984fd20ec to your computer and use it in GitHub Desktop.
useHover typescript
import React, { useEffect, useRef, useState } from "react";
type UseHoverType<T extends HTMLElement> = [React.RefObject<T>, boolean];
function useHover<T extends HTMLElement>(): UseHoverType<T> {
const [value, setValue] = useState(false);
const ref = useRef<T>(null);
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
useEffect(
() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseover", handleMouseOver);
node.addEventListener("mouseout", handleMouseOut);
return () => {
node.removeEventListener("mouseover", handleMouseOver);
node.removeEventListener("mouseout", handleMouseOut);
};
}
},
[ref.current] // Recall only if ref changes
);
return [ref, value];
}
@jackdh
Copy link
Author

jackdh commented Jun 1, 2020

// Usage

function App() {
  const [hoverRef, isHovered] = useHover();

  return (
    <div ref={hoverRef}>
      {isHovered ? '😁' : '☹️'}
    </div>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment