useRef creates a mutable reference that persists across re-renders without triggering a component re-render when mutated.
⊞Code Example
import React, { useRef } from 'react';
export default function SearchBar() {
const inputRef = useRef(null);
const handleFocus = () => {
inputRef.current?.focus();
};
return (
<div className="flex gap-2">
<input
ref={inputRef}
type="text"
placeholder="Search documentation..."
className="px-4 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white"
/>
<button onClick={handleFocus} className="px-4 py-2 bg-slate-800 text-white rounded-xl">
Focus Input (Ctrl+K)
</button>
</div>
);
}
