⚛️ useState vs useRef — What's the Difference in React?
Two commonly used React Hooks are useState and useRef.

ᅠ 📘 Engineering Notes | From Concepts to Code — Post 13 ᅠ When building React applications, we often need to store and manage values.
Two commonly used React Hooks are useState and useRef.
Both can preserve values between renders, but they behave differently.
Let's understand with simple examples! 👇 ᅠ 1️⃣ useState — Managing UI State 🔄
useState stores values that affect what users see on the screen.
When we update state using its setter, React schedules a re-render.
Example:
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}> Count: {count} </button>
Every button click updates the count displayed on the screen.
✅ Stores component state ✅ Triggers UI updates ✅ Useful for counters, forms, and toggles ᅠ 2️⃣ useRef — Storing Values Without Re-Rendering 📦
useRef stores a mutable value that persists between renders.
Unlike useState, changing ref.current does not trigger a re-render.
Example:
const countRef = useRef(0);
function handleClick() { countRef.current += 1; console.log(countRef.current); }
The value increases with every click, but React doesn't re-render because the ref changed.
✅ Preserves values between renders ✅ Does not trigger re-renders ✅ Useful for timers and DOM references ᅠ 3️⃣ Real-World Example — Focusing an Input 🎯
Imagine clicking a button to focus a search field.
const inputRef = useRef(null);
function focusInput() { inputRef.current?.focus(); }
<input ref={inputRef} /> <button onClick={focusInput}>Focus</button>
Here, useRef gives us access to the input element without needing state. ᅠ 4️⃣ Quick Comparison ⚖️
🔹 useState • Stores UI-related state • Updates trigger re-renders • Read the value during rendering
🔹 useRef • Stores mutable references • Updates don't trigger re-renders • Access values using .current ᅠ 💡 My Key Takeaway
Use useState when changing a value should update the UI.
Use useRef when you need to remember a value without triggering a re-render.
Choosing the right Hook helps keep React components clean and predictable.
🚀 Understanding when to use each is more important than simply knowing their syntax. ᅠ 💬 Which Hook do you use more often in your React projects — useState or useRef? ᅠ #ReactJS #SoftwareEngineering #ReactHooks #FrontendDevelopment #JavaScript