I don't understand the underlying behavior of ref system in react hooks.
I understand that useRef will create a constant object where only the current property will change during each render.
I expected createRef to behave the same, but apparently, not:
This code is creating an infinite loop
import React from "react";
export default function App() {
const [count, setCount] = React.useState(0)
const ref = React.createRef()
React.useLayoutEffect(() => {setCount(count => count+1)}, [ref])
return (
<h1 ref={ref}>{count}</h1>
);
}
This code is not:
import React from "react";
export default function App() {
const [count, setCount] = React.useState(0)
const ref = React.useRef()
React.useLayoutEffect(() => {setCount(count => count+1)}, [ref])
return (
<h1 ref={ref}>{count}</h1>
);
}
So, what is the magic behind createRef?
Moreover, I encountered some cases implying measurement of children, where this behavior is getting really problematic. So what is the point in using createRef over useRef?