What is the useRef Hook of React


The useRef
hook is used to persist values across component re-renders.
It is used for DOM manipulation.
useRef is the midway between variables and state values.
Unlike variables, useRef
is persistent across re-renders.
Syntax:-
const myRef = useRef(initial value)
The useRef hook returns an object with a single property - current
You can write changes to the myRef.current
property.
Unlike states, changing the myRef object does not cause the page to re-render. Hence, you should not use it to hold values for UI elements.
useRef usage
The below code is an example of how you can get access to a DOM element via useRef:-
import {useRef} from "react";
export const myComponent = () => {
const myRef = useRef(null);
return {
<input ref = {myRef} />
}
}
When storing references to DOM elements, consider useRef
as a substitute for document.getElementById
of JavaScript. Now, you can perform any action on this input
element from behind the hood.
Happy refing! :)
Subscribe to my newsletter
Read articles from Riya Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
