The useRef hook allows you to create a mutable ref object that persists for the lifetime of the component. You can use it to store and access values that don’t trigger a re-render.
Here’s an example of how to use useRef to access the value of an input element:
import React, { useRef } from 'react'; function InputWithFocus() { const inputRef = useRef(); const handleClick = () => { inputRef.current.focus(); } return ( <div> <input type="text" ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </div> ); }
In this example, we define an InputWithFocus component that creates a ref object with the useRef hook and attaches it to the input element. We use the ref object to focus the input when the “Focus Input” button is clicked.