UseRef — A Side Note to the Official Doc
The following can be read as a side note to the official React Doc

UseRef
The useRef
hook returns a mutable ref object whose .current
property is initialised to the passed argument (initialValue
). The returned object will persist for the full lifetime of the component.
const refContainer = useRef(initialValue);
That sounds confusing right? But in short, useRef
is just like :
- Behave like instance variables, can hold scala values, functions, etc.
- Normally used for adding CSS effect, can be used as checker on component.
A common use case is to access a child imperatively:
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>
</>
);
}
Essentially, useRef
is like a “box” that can hold a mutable value in its .current
property.
The common use cases is to use ref to access Dom
as the above example illustrates.
However, useRef()
is useful for more than the ref
attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
This works because useRef()
creates a plain JavaScript object. The only difference between useRef()
and creating a {current: ...}
object yourself is that useRef
will give you the same ref object on every render. Typically you want to modify refs in event handlers and effects. And note that it can hold a function as well instead of just a scalar value.


