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

Don't paint before measurements are taken #34

Open
Sun-2 opened this issue Jan 7, 2021 · 1 comment
Open

Don't paint before measurements are taken #34

Sun-2 opened this issue Jan 7, 2021 · 1 comment

Comments

@Sun-2
Copy link

Sun-2 commented Jan 7, 2021

On the first render, bounds is obviously filled with 0's.

Is it possible for the 2nd render, with the bounds object filled properly, to happen before the browser paints?

For example, given you want to sync two div's height, the following implementation (with react-use-measure) lets the browser paint after the first render, where the height is 0. Only the second render the synced div jumps to its correct height, which results in a flash.

function Component() {

  const [ref, bounds] = useMeasure();

  return (
    <>
      <div
        ref={ref}
        style={{ backgroundColor: "red", width: "200px", height: "200px" }}
      />
      <div
        style={{
          backgroundColor: "blue",
          width: "200px",
          height: `${bounds.width}px`
        }}
      />
    </>
  );
}

A component like this one, without react-use-measure works just fine, without the flash (properly).

function Component() {
  const ref = useRef<any>();
  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    const ro = new ResizeObserver(([entry], observer) => {
      console.log(entry.contentRect);
      setHeight(entry.contentRect.height);
    })
    ro.observe(ref.current!);
    return () => ro.disconnect();
  }, []);
  return (
    <>
      <div
        ref={ref}
        style={{ backgroundColor: "red", width: "200px", height: "200px" }}
      />
      <div
        style={{
          backgroundColor: "blue",
          width: "200px",
          height: `${height}px`
        }}
      />
    </>
  );
}
@samselikoff
Copy link

Agree – I think this could at least be a config option!

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

2 participants