useRef
is a Hook provided by React that allows you to create a mutable object that persists throughout the lifetime of a component. The object can be accessed and updated within the component, and changes to the object will not trigger a re-render of the component.
The useRef
Hook returns a single value, which is a mutable ref object. This object has a current
property that can be used to store any value, such as a DOM node or a variable.
One common use case for useRef
is to reference a DOM element, which can be accessed and manipulated directly using the ref object's current
property. For example, you could use useRef
to store a reference to an input element and then call the focus()
method on it in response to a user action.
Here's an example of using useRef
to create a ref object and reference a DOM element:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
The useRef
Hook is called to create a ref object inputRef
with an initial value of null
. The ref
attribute is then passed to the input
element, which assigns the reference to the current
property of the ref object. Finally, a button is rendered with an onClick
event handler that calls the focus()
method on the ref object's current
property, which will focus the input element.