Meet React useRef(): The Greatest React Hook
useRef()
is a built-in hook in React that provides a way to access and manipulate the DOM nodes or other mutable values within a component. The useRef()
hook returns a mutable ref object that can be used to store any value, similar to an instance property on a class component.
Here is an example of how useRef()
can be used in a functional component:
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
In this example, we create a ref object called inputRef
using useRef()
. We then attach the ref
attribute to an input element, which allows us to access and manipulate the input's DOM node. In the handleClick()
function, we use the inputRef.current
property to access the input's DOM node and call its focus()
method to give it focus.
useRef()
can also be used to store other mutable values besides DOM nodes, such as a counter or a flag that tracks whether a component is mounted or not. It's important to note that changing the value of a ref object using ref.current = newValue
does not cause a re-render of the component, so it should not be used to store values that affect the component's appearance or behavior.