🧠 Why useRef Doesn’t Cause a Re-render in React Many developers assume useRef behaves like state. But it doesn’t. Example 👇 function Counter() { const countRef = useRef(0); function increment() { countRef.current += 1; console.log(countRef.current); } return ( <button onClick={increment}> Count: {countRef.current} </button> ); } Click the button. Console shows: 1 2 3 But the UI still shows: Count: 0 🔍 Why? useRef does not trigger a re-render. Updating: countRef.current = newValue changes the value, but React does not re-run the component. 🧠 What useRef Is Actually For useRef is mainly used for: Accessing DOM elements Persisting values between renders Storing mutable data that shouldn’t trigger UI updates Example: const inputRef = useRef(); <input ref={inputRef} /> 🎯 Key Rule If the UI needs to update → use state If the value just needs to persist → use ref #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
React useRef Explained: No Re-render
More Relevant Posts
-
🚀 Day 5/30 – State in React One of the most important concepts 🔥 Today I learned: ✅ State stores dynamic data inside a component → It allows components to manage and update their own data ✅ When state changes → React re-renders the UI → React automatically updates only the changed parts (efficient rendering ⚡) ✅ Managed using useState hook → The most commonly used hook in functional components ✅ State updates are asynchronous → React batches updates for better performance 💻 Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prev => prev + 1); // safe update }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); } 🔥 Key Takeaway: State is what makes React components interactive, dynamic, and responsive to user actions. #React #State #FrontendDevelopment #JavaScript #WebDev #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Shipped my latest front-end project — an Async Weather Tracker built with vanilla JS. ☁️ Key features: - Live weather data via OpenWeatherMap API - async/await for all API calls - Search history stored in localStorage - Clean, minimal UI redesign Check it out here 👇 https://lnkd.in/g_kQZ6ad Still learning, still building. #JavaScript #FrontEnd #WebDevelopment #StudentProject
To view or add a comment, sign in
-
-
Stop guessing the order of your console.logs. 🛑 JavaScript is single-threaded. It has one brain and two hands. So, how does it handle a heavy API call, a 5-second timer, and a button click all at once without catching fire? It’s all about the Event Loop, but specifically, the "VIP treatment" happening behind the scenes. The Two Queues You Need to Know: 1. The Microtask Queue (The VIP Line) 💎 What lives here: Promises (.then), await, and MutationObserver. The Rule: The Event Loop is obsessed with this line. It will not move on to anything else until this queue is bone-dry. If a Promise creates another Promise, JS stays here until they are all done. 2. The Macrotask Queue (The Regular Line) 🎟️ What lives here: setTimeout, setInterval, and I/O tasks. The Rule: These tasks are patient. The Event Loop only picks one at a time, then goes back to check if any new VIPs (Microtasks) have arrived. The "Aha!" Moment Interview Question: What is the output of this code? (Most junior devs get this wrong). JavaScript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); The Reality: 1. Start (Sync) 2. End (Sync) 3. Promise (Microtask - Jumps the line!) 4. Timeout (Macrotask - Even at 0ms, it waits for the VIPs) The Pro-Tip for Performance 💡 If you have a heavy calculation, don't wrap it in a Promise thinking it makes it "background." It’s still on the main thread! Use Web Workers if you really want to offload the heavy lifting. Does the Event Loop still confuse you, or did this click? Let's discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🚀 Understanding useRef in React — Simplified! Not all data in React should trigger a re-render. 👉 That’s where useRef becomes powerful. 💡 What is useRef? useRef is a hook that lets you store a mutable value that persists across renders—without causing re-renders. ⚙️ Basic Syntax const ref = useRef(initialValue); 👉 Access value using: ref.current 🧠 How it works Value persists across renders Updating it does NOT trigger re-render Works like a mutable container 🔹 Example const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log(countRef.current); }; 👉 UI won’t update—but value persists 🧩 Real-world use cases ✔ Accessing DOM elements (focus, scroll) ✔ Storing previous values ✔ Managing timers / intervals ✔ Avoiding unnecessary re-renders 🔥 Best Practices (Most developers miss this!) ✅ Use useRef for non-UI data ✅ Use it for DOM access ✅ Combine with useEffect when needed ❌ Don’t use useRef for UI state ❌ Don’t expect UI updates from it ⚠️ Common Mistake // ❌ Expecting UI update countRef.current += 1; 👉 React won’t re-render 💬 Pro Insight 👉 useRef = Persist value without re-render 👉 useState = Persist value with re-render 📌 Save this post & follow for more deep frontend insights! 📅 Day 14/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #useRef #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚨 JavaScript “this” Trap — Arrow Function vs Regular Function const counter = { value: 42, show: () => this.value, }; console.log(counter.show.call({ value: 100 })); // undefined ❗ 💡 What’s happening? Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (usually the global scope). So even when we try to override this using .call(), .apply(), or .bind(), it doesn’t work. 👉 That’s why the result is undefined instead of 100. ✅ When to use Arrow Functions: • When you want to preserve the outer this (e.g., inside callbacks, closures) • In React functional components or array methods (map, filter, etc.) • When you don’t need dynamic context ❌ When NOT to use Arrow Functions: • Object methods that rely on this • Constructors (they can’t be used with new) • Event handlers where this refers to the element • When you need .call(), .apply(), or .bind() 🔥 Fix the issue: const counter = { value: 42, show() { return this.value; }, }; console.log(counter.show.call({ value: 100 })); // 100 ✅ ⚡ Key Takeaway: Arrow functions are not a replacement for regular functions — they’re a different tool. Use them wisely. Misusing them can silently break your logic. #JavaScript #WebDevelopment #Frontend #MERN #CodingTips #CleanCode #reactjs #nodejs
To view or add a comment, sign in
-
-
⚡ Debounce vs Throttle — Optimizing Event Handling in JavaScript Handling frequent events like typing can quickly lead to unnecessary function executions and performance issues if not controlled properly. 🧠 Key Differences: • Normal execution → Runs on every event trigger • Debounce → Executes only after the user stops triggering the event • Throttle → Limits execution to once per specified time interval 💡 Why it matters: Uncontrolled event handling can lead to excessive API calls and degraded performance. Applying the right strategy ensures efficient, predictable, and optimized behavior. ⚡ Takeaway: Use debounce for input fields and search functionality Use throttle for continuous events like scrolling or resizing Choosing the right approach is essential for building high-performance, scalable frontend applications. #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Performance #CleanCode #SoftwareEngineering #Debounce #Throttle
To view or add a comment, sign in
-
⚛️ React Concept: useState Explained with Real Examples The "useState" hook allows you to add state management to functional components. It helps you store and update data that changes over time — like user input, counters, or UI state. Basic syntax: const [state, setState] = useState(initialValue); 🔹 "state" → current value 🔹 "setState" → function to update the value 📌 Common use cases: • Counter functionality • Form inputs • Toggle UI (show/hide) 📌 Best Practice: Always update state using the setter function and avoid directly mutating state. #reactjs #frontenddevelopment #javascript #webdevelopment #softwareengineering
To view or add a comment, sign in
-
-
Interesting comparison between HTMX and React while implementing the same feature 👀 The article shows how a relatively simple UI feature took 3 days in React but only 3 hours using HTMX ⏱️ It’s a good reminder that technology choices can significantly affect complexity and development time. Sometimes a simpler approach can solve the problem more efficiently than adding additional abstraction layers. It also raises interesting questions about when complexity is actually necessary in system design. Curious to see how approaches like HTMX evolve alongside traditional frontend frameworks. 💡 Always interesting to see how different tools approach the same problem. #webdevelopment #softwareengineering #javascript #frontend #backend https://lnkd.in/ecpfhWgW
To view or add a comment, sign in
-
1,200 lines of form code deleted from a production dashboard — and the forms actually work better now. That's what happens when you swap React Hook Form for React 19's built-in Actions + useActionState on the right kind of project. Here's the thing most tutorials won't tell you: this isn't a blanket "RHF is dead" story. It's a "know when to use what" story. → Simple CRUD forms (login, contact, settings)? useActionState + useOptimistic handles it natively. No extra deps, no bundle cost, instant optimistic UI out of the box. → Complex dynamic forms (nested arrays, conditional fields, 50+ field wizards)? React Hook Form still wins. React 19 has no built-in validation beyond HTML attributes — and managing deeply nested field arrays without RHF is pain you don't need. → The middle ground is where it gets interesting. Forms with 5–15 fields and basic Zod validation? You can go either way. We leaned native and didn't look back. The real unlock isn't "drop the library." It's that React's form primitives finally work well enough that you can evaluate each form on its own complexity instead of reaching for RHF by default on every project. Three questions before you refactor: 1. Do any of your forms have dynamic field arrays? 2. Are you using RHF's validation resolver pattern heavily? 3. Is your form state shared across multiple components? If you answered "no" to all three, you might be carrying a dependency you don't need. What's your team's take still all-in on React Hook Form, or have you started migrating simpler forms to Actions? #ReactJS #FrontendDevelopment #WebDev #JavaScript #React19 #FormHandling #DeveloperProductivity
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development