I was going through the hooks documentation when I stumbled upon useRef
.
Looking at their example…
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
…it seems like useRef
can be replaced with createRef
.
function TextInputWithFocusButton() {
const inputRef = createRef(); // what's the diff?
const onButtonClick = () => {
// `current` points to the mounted text input element
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Why do I need a hook for refs? Why does useRef
exist?
ref
is not limited, and can even hold a simple number; But why is.current
required (unlikeuseState
hook)? Found the reason: just to make.current
passable by reference, like a real class's field, without strange setter. (LOL, I wonder how far slower functional vs real class is nowadays.) – Jeremiahjeremias