
Learn how to create a reusable React hook that detects text truncation in UI elements, enabling intelligent tooltips and responsive design adjustments
The Truncation Detection Problem
In modern UIs, we often truncate text with CSS when it exceeds container bounds:
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}This is cool and all but sometimes we need to keep those truncated strings helpful and communicative for our users. To that end it would be helpful to know if our string has been truncated or not. This knowledge could open such opportunities as:
- Showing tooltips only when content is truncated
- Dynamically adjusting layouts
- Providing expand/collapse functionality
Can we actually detect that?
Yes, yes we can!
A very rudimentary attempt could be made by checking element dimensions:
const isTruncated = element.scrollWidth > element.clientWidth
While this works OK, it has several limitations:
- Doesn’t respond to window resizing
- Requires “manual” DOM access
- Definitely lacks React lifecycle awareness
To make this work the best with react we definitely could use a hook.
Solution
For this to work, we need a hook with:
- Type safety with generics
- ResizeObserver for responsiveness
- Simple API
import { type RefObject, useEffect, useRef, useState } from 'react'
interface UseDetectedTruncationOptions {
/** also compare heights: for multi-line truncation (line-clamp) */
multiline?: boolean
}
interface UseDetectedTruncation<RefType> {
ref: RefObject<RefType | null>
isTruncated: boolean
}
export const useDetectedTruncation = <RefType extends HTMLElement>({
multiline = false,
}: UseDetectedTruncationOptions = {}): UseDetectedTruncation<RefType> => {
const [isTruncated, setIsTruncated] = useState(false)
const ref = useRef<RefType>(null)
useEffect(() => {
const element = ref.current
if (!element) return
const check = () => {
const widthCut = element.scrollWidth > element.clientWidth
const heightCut = multiline && element.scrollHeight > element.clientHeight
setIsTruncated(widthCut || heightCut)
}
// fires once on observe(), so no separate initial check
const resizeObserver = new ResizeObserver(check)
resizeObserver.observe(element)
// text can change without the box changing size
const mutationObserver = new MutationObserver(check)
mutationObserver.observe(element, {
childList: true,
subtree: true,
characterData: true,
})
return () => {
resizeObserver.disconnect()
mutationObserver.disconnect()
}
}, [multiline])
return { ref, isTruncated }
}ResizeObserver calls its callback once when observe() starts, so the hook needs no separate initial check. The MutationObserver covers text that changes while the box keeps its size. Pass { multiline: true } for line-clamp truncation, where the text is cut vertically. The | null in the returned ref type is what React 19's types give for useRef<T>(null); on React 18 types, type it as RefObject<RefType>.
Known limits
- scrollWidth and clientWidth are whole pixels. Text cut by a fraction of a pixel (up to about 0.4px) shows an ellipsis, but the hook reports it as not truncated.
- The height comparison can misfire on a single line with a tight line-height (scrollHeight 17 against clientHeight 16 at line-height: 1 in Chromium). That is why multiline is opt-in.
Practical Usage
Here’s how to create a smart tooltip component using our hook:
import { Tooltip, type TooltipProps } from '@your-ui-library'
import { twMerge } from 'tailwind-merge'
import { useDetectedTruncation } from './hook'
interface SmartTooltipProps extends React.HTMLAttributes<HTMLSpanElement> {
tooltipProps: Omit<TooltipProps, 'content'>
content: string
}
export const SmartTooltip = ({
tooltipProps,
content,
children,
className,
...props
}: SmartTooltipProps) => {
const { isTruncated, ref } = useDetectedTruncation<HTMLSpanElement>()
return (
<Tooltip {...tooltipProps} content={isTruncated ? content : undefined}>
<span
ref={ref}
className={twMerge('block truncate', className)}
{...props}
>
{children || content}
</span>
</Tooltip>
)
}The element has to be a block (or inline-block, or a flex or grid child) with a limited width. overflow does not apply to an inline <span>, so the text would never be cut and the hook would have nothing to report.
Performance Considerations
- Cleanup: Properly disconnect observers in the cleanup function to prevent memory leaks.
- Cheap re-checks: setIsTruncated does not re-render when the value is unchanged, so a resize that does not change the answer costs no render.
Testing Strategies
jsdom does not lay anything out: every size is 0 and there is no ResizeObserver. So the test below fakes both and checks the wiring:
- Width overflow reports truncated
- Text that fits reports not truncated
- Heights are ignored unless multiline is set
Whether a browser really cuts the text needs a browser: Playwright or Vitest browser mode.
// @vitest-environment jsdom
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useDetectedTruncation } from './hook'
const Label = ({ multiline }: { multiline?: boolean }) => {
const { ref, isTruncated } = useDetectedTruncation<HTMLSpanElement>({
multiline,
})
return (
<span ref={ref} data-testid="label" data-truncated={isTruncated}>
Some text
</span>
)
}
// jsdom has no layout: every size is 0, so we fake them
const setSizes = (sizes: Partial<Record<string, number>>) => {
for (const [name, value] of Object.entries(sizes)) {
vi.spyOn(Element.prototype, name as 'scrollWidth', 'get').mockReturnValue(
value as number,
)
}
}
describe('useDetectedTruncation', () => {
beforeEach(() => {
// jsdom has no ResizeObserver: call back once on observe(), like browsers do
vi.stubGlobal(
'ResizeObserver',
class {
constructor(private callback: () => void) {}
observe() {
this.callback()
}
disconnect() {}
},
)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('reports truncation when scrollWidth exceeds clientWidth', () => {
setSizes({ scrollWidth: 300, clientWidth: 100 })
render(<Label />)
expect(screen.getByTestId('label').dataset.truncated).toBe('true')
})
it('reports no truncation when the text fits', () => {
setSizes({ scrollWidth: 100, clientWidth: 100 })
render(<Label />)
expect(screen.getByTestId('label').dataset.truncated).toBe('false')
})
it('compares heights only with multiline', () => {
setSizes({
scrollWidth: 100,
clientWidth: 100,
scrollHeight: 60,
clientHeight: 40,
})
const { unmount } = render(<Label />)
expect(screen.getByTestId('label').dataset.truncated).toBe('false')
unmount()
render(<Label multiline />)
expect(screen.getByTestId('label').dataset.truncated).toBe('true')
})
})
Going forward
To make it even sexier, we could consider adding the following features:

Conclusion
The useDetectedTruncation hook provides a clean, reusable solution for a common UI challenge. By encapsulating the detection logic, we can:
- Create more accessible interfaces
- Build smarter components
- Reduce unnecessary tooltip clutter
- Make our UIs more responsive to content changes
Originally published at https://www.pawelkrystkiewicz.pl on November 20, 2024.