A neat custom React Hook that I used in some of my React freelance projects which checks if an elementâs content has overflow (here: vertical overflow):
If you want to detect a horizontal overflow instead, you can exchange the hasOverflow assignment to the following:
In a function component , the custom React hook can be used this way:
The first time the hook returns an undefined, because the state hasnât been set yet.
The custom hook also accepts an optional callback function which fires after the overflow has been checked:
If an elementâs size changes, you could adapt the custom hook to check verify again the overflow, but only if the browser supports the ResizeObserver:
Thatâs it. There may be many ways to improve this custom hook (e.g. initializing the ref within the custom hook and return it from the custom hook to attach it to the element, fire the custom hook only once ), but for my cases it has been sufficient for now.