useState vs useRef in ReactJS

🚀 ReactJS Deep Dive: "useState" vs "useRef" (Most Asked Interview Topic) As a Frontend Engineer, understanding the difference between hooks is not optional — it’s essential. One of the most confusing (and commonly misused) concepts in is: 👉 "useState" vs "useRef" --- ⚔️ Core Difference 🔹 "useState" → Triggers re-render 🔹 "useRef" → Does NOT trigger re-render --- ✅ When to use "useState" 👉 When your data affects UI const [count, setCount] = useState(0); setCount(count + 1); // UI updates 📌 Use cases: - Form inputs - API data rendering - Toggles / UI state - Conditional rendering --- ✅ When to use "useRef" 👉 When you want to store value WITHOUT re-render const countRef = useRef(0); countRef.current += 1; // no re-render 📌 Use cases: - Access DOM (focus input) - Store previous values - Timers / intervals - Avoid unnecessary renders --- 🔥 Real Insight const renderCount = useRef(0); renderCount.current++; console.log(renderCount.current); 👉 Tracks renders without causing new render --- ⚠️ Common Mistakes ❌ Using "useRef" for UI → UI won’t update ❌ Using "useState" for non-UI values → unnecessary re-renders --- 🧠 Golden Rule «"useState" → for UI updates "useRef" → for persistent values without re-render» --- 💬 In real-world apps (dashboards, grids, enterprise systems), choosing the right hook can impact performance significantly. --- Have you ever faced a bug because of wrong hook usage? 👇 Let’s discuss! #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Performance #SoftwareEngineering

To view or add a comment, sign in

Explore content categories