Back to React Hooks
4
useRef
Access DOM elements and persist values between renders
IntermediateCore Concepts
useRefreturns a mutable object that persists across renders- Access the value via
.current - Changing
.currentdoes NOT trigger a re-render - Commonly used for DOM access and storing previous values
Demo 1: DOM Access
Click the button to focus the input without managing focus state:
Demo 2: Persist Values Without Re-render
Type in the input — render count updates but is stored in a ref (no infinite loop!):
Render count: 1
useRef vs useState
useRef
- • Does NOT trigger re-render
- • Mutable via .current
- • For DOM refs, timers, previous values
useState
- • Triggers re-render on change
- • Immutable (use setter)
- • For UI state that should reflect visually
Code
import { useRef } from 'react';
function TextInputWithFocus() {
// Create a ref to store the DOM element
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
// Access the DOM node directly
inputRef.current?.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>
Focus Input
</button>
</div>
);
}