Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect measurements after Next.js soft navigation on mobile #100

Open
jamesvclements opened this issue May 31, 2023 · 0 comments
Open

Comments

@jamesvclements
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant