undefinedfix
Sign in

After adding animation to the react function, is it true that every DOM change in the animation process is a continuous rerender process

Red edited in Sun, 30 Oct 2022
import React, { useState, useRef, useEffect } from "react";
import ResizeObserver from "resize-observer-polyfill";

export function useMeasure() {
  const ref = useRef();
  const [bounds, set] = useState({ left: 0, top: 0, width: 0, height: 0 });
  const [ro] = useState(
    () => new ResizeObserver(([entry]) => set(entry.contentRect))
  );
  useEffect(() => {
    if (ref.current) ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  return [{ ref }, bounds];
}

function App() {
  const [size, setSize] = useState(100);
  const Change = () => {
    setSize(300);
  };
  const [bind, { height: viewHeight }] = useMeasure();
  console.log(bind);
  return (
    <div
      style={{
        background: "blue",
        width: 200,
        height: size
        transition: "height 1s ease-out"
      }}
      {...bind}
      onClick={Change}
    />
  );
}

export default App;

After adding the transition: "height 1s ease out" animation transition attribute, there is animation, but it seems that this function component has been executed many times

As shown in the picture, console.log (bind); this statement has been executed many times, which means that the function component has also been executed so many times. After removing the animation, it becomes the normal twice?

Solve? Is this a normal manifestation of react? Or is there something wrong? If there is a problem, why? How to optimize it?

1 Replies
aleonjhon
commented on Sun, 30 Oct 2022

The problem seems to be known, because the general principle of usemeasure is to store DOM attributes in the state with the resiseobserver API. Due to the continuous monitoring of resiseobserver, the saved DOM attribute state changes constantly. However, this leads to the continuous rerender of react in the process of animation transformation, which leads to the continuous execution of external app components. I understand that.