❓ What is useRef in React? useRef is a React hook that creates a mutable object whose .current property persists across component renders. const ref = useRef(initialValue); Unlike state, updating a ref does not trigger a re-render. ❓ Why is useRef important? useRef allows you to store values that are not part of the rendering lifecycle. This helps maintain performance and keeps components free from unnecessary re-renders. ✔ Persists across renders ✔ Updates synchronously ✔ Does not trigger re-render ❓ When should you use useRef? 📌 Accessing DOM elements Used for focus management, scrolling, or text selection. inputRef.current.focus(); 📌 Persisting values across renders Ideal for timers, intervals, counters, and external library instances. 📌 Storing previous values Helpful for comparing current and previous state or props. 📌 Preventing unnecessary re-renders Best for frequently changing values that do not impact the UI. ❓ When should you NOT use useRef? 🚫 When changes must be reflected in the UI 🚫 When re-rendering is required after updates In these cases, useState is the better choice. 🎯 Key Takeaway Use useRef when you need to persist or update values without affecting the component’s render cycle. It complements useState and helps write more efficient React components. #React #JavaScript #ReactHooks #FrontendDevelopment #WebDevelopment
React useRef Hook: Persistent Values Across Renders
More Relevant Posts
-
⚛️ React Rendering — finally made sense for me today For a long time, I thought React updates the UI in one go. Turns out… that’s not how it actually works 🙂 React does its job in two clear steps: 👉 First, it thinks (Render Phase) 👉 Then, it acts (Commit Phase) In the render phase, React only decides what should change. No DOM updates. No side effects. Just calculations. In the commit phase, React updates the DOM and runs effects. This is where things actually appear on the screen. Understanding this small difference helped me: - avoid unnecessary API calls - fix repeated renders - write cleaner useEffect logic If React rendering ever felt confusing, this breakdown might help you too. 📌 Saved this as a carousel for quick revision 💬 Curious to know — when did React “click” for you? #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #LearningInPublic #IndianDevelopers
To view or add a comment, sign in
-
React 19 lets you delete useEffect for DOM logic. 👇 👇 For years, integrating third-party DOM libraries (like GSAP, ResizeObserver, or vanilla JS animations) required a specific dance: 1. Create a useRef. 2. Create a useEffect. 3. Check if (ref.current). 4. Return a cleanup function. It separated the "Element" from the "Logic" that controlled it. React 19 introduces Ref Callback Cleanup. ❌ The Old Way: You had to synchronize a mutable ref with an effect. It was verbose and prone to "stale closure" bugs if you forgot dependencies. ✅ The Modern Way: Pass a function to the ref prop. React runs this function when the node mounts. If you return a function, React will automatically run it when the node unmounts. Why this is cleaner: 📉 Less Code: Logic is co-located with the element it affects. 🧠 No Hooks: You don't need useRef or useEffect for simple DOM integrations. ⚡ Safe: Handles node mounting/unmounting lifecycles perfectly. Note: This is perfect for things like ResizeObserver, IntersectionObserver, or auto-focus logic. #ReactJS #React19 #WebDevelopment #Frontend #JavaScript #CleanCode #SoftwareEngineering #TechTips #ReactHooks #Hooks #ReactTips #FrontrendDeveloper #DevloperTips
To view or add a comment, sign in
-
-
⚛️ React 19 lets you delete useEffect for DOM logic. 👇 👇 For years, integrating third-party DOM libraries (like GSAP, ResizeObserver, or vanilla JS animations) required a specific dance: 1. Create a useRef. 2. Create a useEffect. 3. Check if (ref.current). 4. Return a cleanup function. It separated the "Element" from the "Logic" that controlled it. React 19 introduces Ref Callback Cleanup. ❌ The Old Way: You had to synchronize a mutable ref with an effect. It was verbose and prone to "stale closure" bugs if you forgot dependencies. ✅ The Modern Way: Pass a function to the ref prop. React runs this function when the node mounts. If you return a function, React will automatically run it when the node unmounts. Why this is cleaner: 📉 Less Code: Logic is co-located with the element it affects. 🧠 No Hooks: You don't need useRef or useEffect for simple DOM integrations. ⚡ Safe: Handles node mounting/unmounting lifecycles perfectly. Note: This is perfect for things like ResizeObserver, IntersectionObserver, or auto-focus logic. #ReactJS #React19 #WebDevelopment #Frontend #JavaScript #CleanCode #SoftwareEngineering #TechTips #ReactHooks #Hooks #ReactTips #FrontrendDeveloper #DevloperTips
To view or add a comment, sign in
-
-
🧠 Is setState 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 or 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 in React? Short answer 👉 setState is 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 — by design. React doesn’t update state immediately. Instead, it schedules state updates and batches multiple updates together to avoid unnecessary re-renders and improve performance. 𝘌𝘹𝘢𝘮𝘱𝘭𝘦:– setCount(count + 1); console.log(count); 𝘖𝘶𝘵𝘱𝘶𝘵:- 0 𝗪𝗵𝘆? Because setState does not update the value instantly — the current render still holds the old state. 🔁 𝗕𝗮𝘁𝗰𝗵𝗶𝗻𝗴 𝗶𝗻 𝗮𝗰𝘁𝗶𝗼𝗻 setCount(count + 1); setCount(count + 1); 𝗥𝗲𝘀𝘂𝗹𝘁 👉 1 (not 2) Both updates read the same stale state, and React batches them into a single render. ✅ The correct pattern (when state depends on previous state) setCount(prev => prev + 1); setCount(prev => prev + 1); 𝗥𝗲𝘀𝘂𝗹𝘁: 2 This works because React provides the latest queued state to each update. 🧠 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 setState doesn’t change state immediately. It requests a state change — React decides when to apply it. This behavior enables better performance, smoother UI, and concurrent rendering. 👀 𝗕𝘂𝘁 𝗵𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝘁𝘄𝗶𝘀𝘁... 👉 setState can be synchronous in React — but only in very specific situations and for a specific purpose. I’ll cover when, why, and whether you should ever use it in my next post. Stay tuned 🚀 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactHooks #Performance #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 𝐕𝐮𝐞’𝐬 𝐕𝐚𝐩𝐨𝐫 𝐌𝐨𝐝𝐞: 𝐓𝐡𝐞 𝐅𝐮𝐭𝐮𝐫𝐞 𝐨𝐟 𝐔𝐥𝐭𝐫𝐚-𝐋𝐢𝐠𝐡𝐭 𝐅𝐫𝐨𝐧𝐭𝐞𝐧𝐝 𝐑𝐞𝐧𝐝𝐞𝐫𝐢𝐧𝐠 ✨ Vapor Mode is an upcoming optimization in Vue.js that removes the Virtual DOM entirely and compiles components directly to native DOM operations. 🔥 𝐖𝐡𝐲 𝐕𝐚𝐩𝐨𝐫 𝐌𝐨𝐝𝐞 𝐌𝐚𝐭𝐭𝐞𝐫𝐬 🔸🚫 Zero Virtual DOM → no diffing, no overhead 🔸📦 Smaller bundle size → faster page loads 🔸⚡ Near-vanilla JS performance → blazing-fast runtime 🔸🧠 Compile-time optimizations → less work for the browser ⚡ 𝐖𝐡𝐚𝐭 𝐂𝐡𝐚𝐧𝐠𝐞𝐬 𝐟𝐨𝐫 𝐃𝐞𝐯𝐞𝐥𝐨𝐩𝐞𝐫𝐬? 🔹✍️ Write standard Vue templates 🔹🔁 Same reactivity system 🔹🧩 No runtime VDOM cost 🔹🚀 Performance close to hand-written DOM code 🧠 𝐁𝐢𝐠 𝐏𝐢𝐜𝐭𝐮𝐫𝐞 ✨ Vapor Mode proves that modern frameworks don’t have to trade performance for developer experience. 🌸 Vue is pushing the boundary where DX ⚡ + Speed 🚀 coexist — without forcing developers to write low-level code. 💡 Ideal for: 🔸 🎯 Performance-critical apps 🔸 🧩 Embedded widgets 🔸 🔮 Future-proof frontend architectures 🔥 Vue isn’t just evolving — it’s redefining what a framework can be. #VueJS #Frontend #WebPerformance #JavaScript #VaporMode #WebDevelopment #PerformanceEngineering Zignuts Technolab
To view or add a comment, sign in
-
-
🎯 Most Developers Use React — But Misunderstand What “Render” Actually Means A lot of React confusion starts with one overloaded word: render. People hear “render” and imagine the browser instantly repainting the screen every time something runs. That’s not what React rendering really means. Here’s the clean mental model — in under a minute 👇 When React renders a component, it is mainly doing this: ➡ Reading your component function ➡ Executing the JSX logic ➡ Producing a new UI description ➡ Comparing it with the previous one ➡ Updating only the changed parts in the real DOM Rendering is a calculation step first — not a direct DOM update. Also, render is not a one-time event. It happens multiple times during a component’s lifecycle: ✅ First time component appears → Initial render (mount) ✅ When state changes → Re-render ✅ When props change → Re-render ✅ When parent re-renders → Child may re-render Important distinction: Mount = first render Update = every render after that Another key point many miss 👇 React does NOT blindly rewrite the entire DOM on every render. It updates a lightweight virtual tree, runs a diff, and patches only what changed. That selective update is what keeps React UIs fast and predictable. If you understand what render truly means, topics like memoization, re-renders, and performance optimization become much easier to reason about. Clarity beats memorization every time. 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content. #ReactJS #FrontendDevelopment #ReactConcepts #VirtualDOM #ReRendering #WebDevelopment #JavaScript #FrontendEngineering #UIPerformance #ReactInterview
To view or add a comment, sign in
-
🚀 Day 8 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 8) Why does JavaScript remember variables even after a function finishes? The answer is Closure. Let’s understand this using a real-world example from React: useState. A simplified mental model of useState (conceptual) function useState(initialValue) { let state = initialValue; function setState(newValue) { state = newValue; render(); // re-render component } return [state, setState]; } Here, setState is a closure. It remembers state even after useState finishes execution. Example: Counter Component function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } Every render is a new function call. So how does React remember count? Let’s go step by step. Render 1 – Initial Mount 1. React calls the component: Counter(). 2. useState(0) runs and creates a state slot outside the function (heap/fiber). 3. count is set to 0 and setCount is returned as a closure. 4. JSX is rendered and UI shows Count: 0. User Clicks the Button 1. Browser triggers a click event. 2. React handles the event via its synthetic event system. 3. setCount(count + 1) is called. 4. React updates internal state and schedules a re-render. Render 2 – After State Update 1. Counter() runs again. 2. Local variables are recreated, but state is preserved. 3. useState does not reinitialize; it reads existing state from memory. 4. count is now 1 and UI updates accordingly. Final Takeaway The component function re-runs on every render, but state survives because React stores it outside the function. setState works because it is a closure pointing to that preserved state. Closures are the reason useState works. #javascript #closure #reactjs #reacthooks #frontend #webdevelopment
To view or add a comment, sign in
-
Creating a Smart Sticky Navbar with React + Tailwind CSS! Ever wondered how to make a navbar that hides on scroll down and shows on scroll up? I recently built a responsive scroll navbar in React: Scroll down → navbar hides Scroll up → navbar appears Responsive design: Desktop → navbar at the top Mobile → navbar at the bottom Here’s the approach I used: Track scroll position using window.scrollY and useRef. Compare current scroll vs last scroll to determine the scroll direction. Use Tailwind classes (translate-y-0 / -translate-y-full) and in responsive (translate-y-full) with transition-all for smooth sliding. Handle responsive behavior with lg:block and lg:hidden classes. Result: Smooth, professional-looking sticky navbar that works on desktop and mobile. Full source code:https://lnkd.in/gy-yCW29 #ReactJS #TailwindCSS #FrontendDevelopment #WebDevelopment #WebDesign #ResponsiveDesign #UIUX #JavaScript #React #CSS #WebDevTips #Programming #Frontend #StickyNavbarReveal #ReactComponents
To view or add a comment, sign in
-
🧠 How Browsers Actually Work (What Every Frontend Dev Should Know) When you hit Enter after typing a URL, the browser doesn’t “open a page”… it builds one from scratch. 🔹 Step 1: Finding the Server (DNS) Browser converts the domain into an IP address so it knows where to talk. 🔹 Step 2: Fetching Resources An HTTP request is sent → server responds with HTML, CSS, JS, fonts, images. 🔹 Step 3: Building the Page HTML → DOM CSS → CSSOM DOM + CSSOM → Render Tree Then comes Layout (sizes & positions) and Paint (pixels on screen). 🔹 Step 4: JavaScript Takes Control JS runs in the browser engine, can block rendering, manipulate the DOM, attach events, and call APIs. 🔹 Step 5: The Event Loop Handles async tasks (callbacks, promises, timers) so heavy JS doesn’t freeze the UI. 💡 Why this matters If you understand this flow, you automatically write: Faster UIs Fewer re-renders Better loading strategies Cleaner React / Next.js apps 👉 Browsers are rendering engines + JS runtimes + networking layers, not just viewers. If frontend is your craft—browser internals are your foundation 🚀 #FrontendEngineering #JavaScript #WebPerformance #ReactJS #NextJS
To view or add a comment, sign in
-
I just finished Frontend Masters “A Tour of JavaScript & React Patterns” and the biggest mindset shift for me was this: Most React “performance problems” are actually rendering problems. Not “React is slow”, but “I accidentally made more of the tree render than needed”. A few things I’m taking away and actively applying: ✅ Context is not a state manager It is a delivery mechanism. If the value changes often, it becomes a re-render broadcaster. That is perfect for “rarely changes” state (theme, locale, auth), risky for high frequency state. ✅ The fastest component is the one that does not re-render Before reaching for memo everywhere, I ask: Can I move state down? Can I split the provider? Can I pass a stable callback? Can I avoid creating new objects in props? ✅ Render cost is usually in the children Even small parent changes can re-render expensive lists, charts, tables. Splitting components and isolating heavy parts pays off more than micro-optimizing one hook. ✅ Patterns are about shaping render boundaries Custom hooks, compound components, provider splitting, controlled vs uncontrolled components. These are not just “clean code” choices. They decide how much UI updates when data changes. And a big one outside the component tree: ✅ Performance starts before React even runs Choosing the right rendering strategy changes the whole user experience: CSR when you need app-like interactivity and data is truly user-specific SSR when you need fast first paint plus fresh data per request SSG when content is stable and you want maximum speed ISR when you want SSG speed but still keep content reasonably fresh without rebuilding everything Simple rule I like now: Architecture is often performance in disguise, both in your component tree and in your rendering strategy. #react #nextjs #javascript #performance #frontend #webdevelopment #softwareengineering
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