Middle
What is the use of the useRef hook?
sobes.tech AI
Answer from AI
The useRef hook in React is used to create a mutable object that persists across component renders. Main uses of useRef:
- Storing a reference to a DOM element for direct access (e.g., focusing on an input).
- Saving any mutable value that does not trigger a re-render when changed.
Example of using useRef to access the DOM:
import React, { useRef } from 'react';
function InputFocus() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus on input</button>
</>
);
}
Thus, useRef allows storing data or references that do not affect the component's render lifecycle.