The useRef hook returns a mutable ref object whose .current property is initialized to the passed argument.
useRef serves two distinct purposes in React:
| Feature | useState |
useRef |
|---|---|---|
| Updating Value | Triggers component re-render | Does NOT trigger re-render |
| Access Syntax | stateVariable |
refVariable.current |
| Use Case | Reactive UI state rendering | DOM manipulation, timers, instance flags |
import React, { useRef, useState, useEffect } from 'react';
export default function RefDemo() {
// 1. DOM Reference for Input Focus
const inputRef = useRef(null);
// 2. Mutable Reference for Storing Timer ID (Does not trigger re-renders)
const timerRef = useRef(null);
const [seconds, setSeconds] = useState(0);
const handleFocus = () => {
// Access native HTML input DOM node directly
inputRef.current?.focus();
};
const startTimer = () => {
if (timerRef.current !== null) return;
timerRef.current = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
};
const stopTimer = () => {
clearInterval(timerRef.current);
timerRef.current = null;
};
useEffect(() => {
return () => clearInterval(timerRef.current); // Cleanup timer on unmount
}, []);
return (
<div className="card">
<h3>DOM Ref Focus Example</h3>
<input ref={inputRef} type="text" placeholder="Click button to focus..." />
<button onClick={handleFocus}>Focus Input Field</button>
<hr />
<h3>Timer Ref: {seconds}s</h3>
<button onClick={startTimer}>Start Timer</button>
<button onClick={stopTimer}>Stop Timer</button>
</div>
);
}
ref.current During Render: Avoid mutating or reading ref.current inside the component JSX rendering body. Perform ref mutations only inside useEffect or event handlers.Write a component using useRef that counts how many times the component has rendered without triggering additional renders.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With