Mar 25th, 2022 - written by Kimserey with .
Ref
hook in React can be used to keep a mutable reference across multiple renders. In today’s post we will see how we can use useRef
hook and when they are useful.
useRef
HookA Ref
is a reference to a mutable variable which is independent from the rendering. The object returned is a reference to a variable which will live for the full lifetime of the component.
We can create ref using useRef
:
1
const nameRef = useRef<string>("tom");
Then we can reference the variable directly with .current
:
1
cosnole.log(nameRef.current);
A common usecase in React is to use ref to reference a DOM element, for example setting the focus on a input when a component is first displayed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const TextInputWithFocusButton: React.FC = () => {
const inputEl = useRef<any>(null);
const focusOnInput = () => {
if (inputEl.current) {
inputEl.current.focus();
}
};
useEffect(() => {
focusOnInput();
}, []);
return <input ref={inputEl} type="text" />;
};
const App: React.FC = () => {
return <TextInputWithFocusButton></TextInputWithFocusButton>;
};
export default App;
We can see how input
accepts a ref
which is set from inside to the HTML element. We can then access it through the ref.
More generally, a ref
can be used to store and reference anything that needs to survive render, or always be available at any point disregarding the render cycle. States are also persisted across render but the difference being that a state change will trigger a render while ref
do not trigger render.
Without ref
, we wouldn’t be able to persist the value for example we may be tempted to create a regular variable at the top of our component:
1
let nameRef = 'tom";
But the problem with that is that if the component re-render for any reason; a props change or state change or a parent re-render, nameRef
will reset to 'tom'
.
And that concludes today’s post!
In today’s post we saw how we can use useRef
to keep a mutable variable around during the lifetime of the component. I hope you liked this post and I’ll see you on the next one!