Skip to content

Instantly share code, notes, and snippets.

@tlux
Created January 3, 2025 18:05
Show Gist options
  • Save tlux/b22c60ce7cc773ebc5fd2f8b6e230984 to your computer and use it in GitHub Desktop.
Save tlux/b22c60ce7cc773ebc5fd2f8b6e230984 to your computer and use it in GitHub Desktop.
React hook to detect overflow on a ref
import { type RefObject, useEffect, useState } from 'react';
function checkOverflow(el: HTMLElement | null): boolean {
if (!el) return false;
return el.offsetHeight < el.scrollHeight || el.offsetWidth < el.scrollWidth;
}
export function useHasOverflow(ref: RefObject<HTMLElement | null>) {
const [overflow, setOverflow] = useState(false);
useEffect(() => {
const handler = () => {
setOverflow(checkOverflow(ref.current));
};
handler();
window.addEventListener('resize', handler, true);
return () => {
window.removeEventListener('resize', handler, true);
};
}, [ref]);
return overflow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment