Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/perf-underlinenav-item-observer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@primer/react': patch
---

perf(UnderlineNav): Batch layout reads and add comment about ResizeObserver throttling

- UnderlineNavItem: Batch getBoundingClientRect and getComputedStyle reads
- UnderlineNav: Add comment noting ResizeObserver callbacks are now throttled
1 change: 1 addition & 0 deletions packages/react/src/UnderlineNav/UnderlineNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ export const UnderlineNav = forwardRef(

useOnOutsideClick({onClickOutside: closeOverlay, containerRef, ignoreClickRefs: [moreMenuBtnRef]})

// ResizeObserver callbacks are now throttled with rAF for better INP
useResizeObserver((resizeObserverEntries: ResizeObserverEntry[]) => {
const navWidth = resizeObserverEntries[0].contentRect.width
const moreMenuWidth = moreMenuRef.current?.getBoundingClientRect().width ?? 0
Expand Down
14 changes: 9 additions & 5 deletions packages/react/src/UnderlineNav/UnderlineNavItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,15 @@ export const UnderlineNavItem = forwardRef(
) as HTMLElement
const text = content.textContent as string

const iconWidthWithMargin = icon
? icon.getBoundingClientRect().width +
Number(getComputedStyle(icon).marginRight.slice(0, -2)) +
Number(getComputedStyle(icon).marginLeft.slice(0, -2))
: 0
let iconWidthWithMargin = 0
if (icon) {
// Batch all layout reads: getBoundingClientRect and getComputedStyle together
const iconRect = icon.getBoundingClientRect()
const iconStyle = getComputedStyle(icon)
// Use || 0 fallback for edge cases where margin might be 'auto' or non-numeric
iconWidthWithMargin =
iconRect.width + (parseFloat(iconStyle.marginRight) || 0) + (parseFloat(iconStyle.marginLeft) || 0)
}

setChildrenWidth({text, width: domRect.width})
setNoIconChildrenWidth({text, width: domRect.width - iconWidthWithMargin})
Expand Down
Loading