I'm confused about the useRef behavior.
- setState on Parent element
- render Children
- 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);
});
}
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