What is the difference between useRef and useState in React?
Quick answer
Updating state triggers a re-render, while changing a ref's .current value does not; use state for data shown on screen and refs for DOM access or values that must persist without causing renders.
useRef returns a mutable object whose .current property lives for the whole life of the component. Typical uses are holding a DOM node (to focus an input or measure an element), storing a timer ID, or remembering the previous value of a prop.
Because React does not know when you change a ref, the UI will not update. If a value affects what the user sees, it belongs in state. Avoid reading or writing ref.current during rendering, except for lazy initialisation.
function SearchBox() {
const inputRef = useRef(null);
const [query, setQuery] = useState(""); // changes the UI
return (
<>
<input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);
}