What is useRef and how is it different from useState?
useRef
is a Hook that lets you persist mutable values across renders without causing a re-render.
Key differences between useRef
and useState
:
Aspect | useRef | useState |
---|---|---|
Causes re-render on update? | ❌ No | ✅ Yes |
Usage | Accessing/managing DOM elements, persisting values between renders | Managing reactive UI state |
Common use cases | Focus input fields, track previous props/state, store timers | UI updates (e.g., toggling modals, changing text) |
Example using useRef
to focus an input:
import { useRef } from 'react'; function FocusInput() { const inputRef = useRef(); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </> ); }