react-use-measure
react-use-measure copied to clipboard
Incorrect measurements after Next.js soft navigation on mobile
I'll add more details when I have the chance, but incase anyone stumbles across this in the meantime: I was using measure in my Next.js 13.4.x site with app router and for some reason, the widths returned from useMeasure() were incorrect after soft navigation. They were correct on initial load of the page. Then I navigated to another page and navigated back and they were around 8px (they should've been 290px). This only happened on mobile.
As a temporary fix I added a custom use measure hook without any debouncing:
import { useState, useRef, useLayoutEffect, RefObject } from "react";
type Rect = {
x: number;
y: number;
width: number;
height: number;
};
type UseMeasureReturnType = [RefObject<HTMLElement>, Rect];
export function useMeasure(): UseMeasureReturnType {
const [rect, setRect] = useState<Rect>({ x: 0, y: 0, width: 0, height: 0 });
const ref = useRef<HTMLElement | null>(null);
useLayoutEffect(() => {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
function handleResize() {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
if (ref.current !== null) {
setRect(ref.current.getBoundingClientRect());
}
/* todo – ideally we could debounce this, but that breaks during soft nav */
}, 0);
}
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return [ref, rect];
}
And that seems to do the trick, but there's likely something weirder going on here.