0
votes

I'm confused about the useRef behavior.

  1. setState on Parent element
  2. render Children
  3. Listen only once, but invoke callback twice. (in Children)
  if (ref.current) {
    console.log("listen");
    ref.current.addEventListener("click", (event) => {
      console.log("xxxx click");
      // setCount(count + 1);
    });
  }

enter image description here

But It works fine, when I use useEffect instead. Listen once, invoke callback once.

  useEffect(() => {
    if (!ref.current) return;
    console.log('listen');
    ref.current.addEventListener("click", (event) => {
      console.log("xxx click");
      // setCount(count + 1);
    });
  }, [ref]);

Codesandbox https://codesandbox.io/s/exciting-platform-v4ugq?file=/src/comp.jsx

1

1 Answers

0
votes

This is because your app is wrapped in strict mode, and in strict mode the setstate will render twice, try removing the strict mode in index.js, this solve the issue

For more info

enter image description here