Today we will learn what the useRef hook does and how to use it in the React library.
The useRef Hook provides a way to directly access a DOM (Document Object Model) node in a functional component. So ref here represents "reference". To use the Ref Hook to access a DOM node, follow these steps.
First, you need to import the useRef Hook from the react package:
import { useRef } from "react"
useRef(initialValue) returns a reference that is a replaceable ref object. This returned object will be persistent for the entire lifetime of the component.
const refObject = useRef(initialValue)
Now, to access the required DOM element, let's pass a ref attribute to this element and assign refObject:
<input ref={refObject} type="text" />
Now, we can access the DOM node using refObject.current.
import React, { useState, useEffect, useRef } from "react"
export default function App() {
const [timer, setTimer] = useState(0)
const timerRef = useRef()
useEffect(() => {
const timerId = setInterval(() => {
setTimer(prevTimerValue) = prevTimerValue + 1
}, 1000)
timerRef.current = timerId
}, [])
return (
<div>
<p> Timer: {timer}</p>
<button onClick={() => clearInterval(timerRef.current)}>Clear TImer</button
</div>
);
}
Here, Ref Hook is used to add focus to the input text box. After the component is rendered to the screen, useEffect runs, and since inputRef.current holds the DOM element, inputRef.current.focus() moves the cursor to the input text box.
Accessing a DOM node using the ref attribute is not the only use of useRef. Because the Ref Hook returns a mutable ref object whose .current property can hold a value for the entire lifetime of the component, you can use it to hold any mutable value that can be used later.
useRef() creates a plain JavaScript object, but the difference between useRef() and creating an object with a current property {current: ...} is that Ref Hook gives you the same ref object every time you render. Also, changing the .current property does not cause it to render again, and so useRef does not notify you when its contents change.
In this article, I tried to explain how the useRef hook can be used. See you in the next article.
No comments yet