useRef()
Hook allows you to persist values between renders.
- It can be used to store a mutable (change after created) value that does not cause a re-render when updated.
- It can be used to access a DOM element directly.
- If component re-render the value in
useRef()
is persist. useRef()
only returns one item. It returns an Object called current.
Accessing DOM Elements
It will focus on the input box when click on the Focus Input button.
import { useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
Use Case
- References DOM elements
- Preserves value between renders
- Stores mutable values
- Caching values
- Accessing previous state or props
- Managing focus, text selection, or animations