Junior — Middle
Can you explain how useRef is implemented in React and what it is used for?
sobes.tech AI
Answer from AI
In React, the useRef hook is used to create a mutable object that preserves its value between component renders, but changing this value does not trigger a re-render.
Main uses of useRef:
- Storing a reference to a DOM element for direct access.
- Storing any mutable value that needs to be preserved between renders without triggering an update.
Example of usage for DOM access:
import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus on input</button>
</>
);
}
Here, inputRef holds a reference to the input DOM element, allowing programmatic focus.
useRef can also be used to store any values, such as a counter, that do not affect the UI.