Loading Depth Study
Preparing your workspace
useRef returns a mutable ref object whose value persists across renders and can also point to a DOM element.
useRef is useful when a component needs to remember a value without causing a re-render when that value changes. It is also commonly used to access DOM elements for actions such as focusing an input, measuring an element, or integrating with browser APIs. Updating ref.current does not trigger a re-render. Because of this, refs should not be used as a replacement for state when the value needs to appear in the UI.
A search page can use a ref to automatically focus the search field when the page opens.
import { useEffect, useRef } from 'react';
export default function SearchBox() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<input
ref={inputRef}
placeholder="Search courses"
/>
);
}The search input receives focus automatically after the component appears.