React’s useRef Hook allows us to access and interact with elements in the DOM directly. It retains its mutable .current property across multiple renders, making it a great tool for preserving values without re-rendering components.
Here’s a simple example of how useRef can be used:
import React, { useRef } from 'react';
function ExampleComponent() {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus the input</button>
</div>
);
}
export default ExampleComponent;
In this example, useRef is used to create a reference (inputRef) to an input element. The handleClick function triggers a focus on this input when the button is clicked.
Remember, useRef does not notify you when its content changes. Mutating the .current property won’t cause a re-render. If you need to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.