The `useRef` hook is a way to create a reference to a DOM element in a functional component in React. It returns a mutable ref object whose `.current` property is initialized to the passed argument (`initialValue`). The value of the `.current` property will persist between the re-renders of the component.
Here is an example of how you might use the `useRef` hook to get a reference to an input element and focus it when a button is clicked:
import { useRef } from 'react';
function Example() {
const inputEl = useRef(null);
const focusInput = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={focusInput}>Focus the input</button>
</>
);
}
Note: the `ref` attribute is not a standard attribute, so it should not be used with JSX elements. Instead, you should pass a callback function to the `ref` attribute, which will be called with the DOM element when the component mounts. The `useRef` hook makes it easy to use this callback pattern.
The `useRef` hook can also be used to store a value that doesn't need to be re-rendered when the component updates. For example, you might use it to store a timer ID when setting up an interval:
import { useRef } from 'react';
function Example() {
const timerID = useRef();
useEffect(() => {
timerID.current = setInterval(() => {
console.log('Interval fired');
}, 1000);
return () => clearInterval(timerID.current);
}, []);
return (
<>
{/* ... */}
</>
);
}
Comments (0)