In this post let's talk about!!!!
UseRef
- UseRef allow us to access DOM elements.
- Create mutable variables which will not re-render the component.
No worries!!!
This is not only theory....
Let's make our first practice.
- The first use case of UseRef is to create a mutable variable without causing re render.
Count the renders of a input with useRef
And the code for this:
import {useState, useEffect, useRef} from "react"; export default function App() { const [name, setName] = useState(""); const count = useRef(0); useEffect(() => { count.current = count.current + 1; }) return ( <> <input type="text" onChange={ (e) => setName(e.target.value) } /> <h2>Name: {name}</h2> <h2>Renders: {count.current}</h2> </> ) } We are using useRef to add the count var and when the input changes, we are increasing in one the count.
- The second use case, Accessing the DOM elements.
The easiest way to change the dom in React is with useRef.
Let's check the next code:
import {useRef} from "react"; export default function App() { const inputElementRef = useRef(null); const handleClick = () => { inputElementRef.current.value = "Hello World"; } return ( <> <input type="text" ref={inputElementRef} /> <button onClick={handleClick}>Change DOM input!</button> </> ) } It will show this:
As we can see, the inputElementRef is declared with useRef(null) and then we can change the value after clicked only with this line:
inputElementRef.current.value = "Hello World";
A piece of cake!!
Finally in the same way, if you want to change the style of the input for example:
The width and focus:
We do that with this code:
const handleClick = () => { inputElementRef.current.value = "Hello World"; inputElementRef.current.style.width = '500px'; inputElementRef.current.focus(); } Conclusion:
const myVar = useRef(initialValue);
myVar.current to update myVar.
- useRef is a hook to allow us to create mutable variables which don't cause re-render.
- Very useful to direct access DOM elements.



Top comments (0)