The two ways of defining, refs are not equivalent.
Consider the first example
const CompA = () => {
let _input;
return (
<input ref={el => _input = el} type="text" />
);
}
In this example, whenever, CompA re-renders, as new variable _input
is created and for instance if you have a useEffect in CompA which is meant to run on initial render and it executes something at an interval using this ref variable it would lead to inconsitencies.
Now consider second case
const CompA = () => {
const _input = useRef(null);
return (
<input ref={_input} type="text" />
);
}
In this case, even though the _input variable is created on each render, useRef
ensures that it receives the same reference that it receives the first time and not initialise it again. useRef
is the right way to define refs for functional Components
. For class components you can use createRef
or the callback pattern you mention
useEffect()
hook. Using a variable instead of a ref can cause unintended extra triggerings of theuseEffect()
hook in question. – Butterfat