🧠 How useRef keeps the previous state value in React In React, components re-render when state changes, but not everything is recreated on every render. useRef gives you a persistent container whose value survives across renders without causing re-renders. 🔑 Important rules to remember useState Triggers a re-render when updated Values are recalculated on every render useRef Persists the same object between renders Updating .current does not trigger a re-render useEffect Runs after the render is committed to the DOM Never runs during rendering 🔄 Step-by-step render lifecycle Initial render count = 0 prevCountRef.current = undefined UI renders: Now: 0 Before: undefined After render useEffect runs prevCountRef.current = 0 After clicking the button setCount(1) is called React schedules a re-render Component re-renders: count = 1 prevCountRef.current = 0 (previous value) UI displays: Now: 1 Before: 0 After this render useEffect runs again prevCountRef.current = 1 (stored for next render) 🧩 Why this works Because the effect runs after rendering, the ref is updated after the UI has already used the old value. This timing allows the ref to act as a “memory” of the previous render. 💡 Mental model State = causes renders Render = reads refs Effect = writes refs ⚠️ Why not use state for this? Using state to store the previous value would: Trigger another re-render Risk infinite render loops Add unnecessary complexity useRef avoids all of that ✅ Final takeaway useRef persists data across renders without re-rendering, and useEffect updates it after render — making it perfect for tracking previous values. #React #ReactJS #JavaScript #ReactHooks #useRef #useEffect #useState #FrontendDevelopment #WebDevelopment #SoftwareEngineering
React useRef persists state between renders
More Relevant Posts
-
𝗧𝗼𝗽𝗶𝗰 𝟬𝟱: 𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝘁 𝗥𝗲𝗻𝗱𝗲𝗿𝗶𝗻𝗴 & 𝗧𝗶𝗺𝗲 𝗦𝗹𝗶𝗰𝗶𝗻𝗴 The Summary: Traditionally, rendering in JavaScript was a "blocking" operation. Once the framework started updating the UI, it couldn't be stopped until it was finished, often leading to frozen screens during heavy updates. Concurrent Rendering and Time Slicing change this by allowing the framework to pause, resume, or even abandon a render to prioritize user input. • The Crux: Imagine a long-running task as a single, massive loaf of bread that blocks the kitchen. Time Slicing cuts that loaf into thin slices (usually <5ms). After "baking" each slice, the framework checks the "orders" (the browser's main thread). If a user clicked a button or started typing, the framework pauses the render, handles the interaction, and then returns to finish the bread. • The Deep Insight (Architect's Perspective): This shifts the UI from a "Push" model to a "Pull" model. In a "Push" model, the framework blindly forces updates to the screen as fast as it can. In a "Concurrent" model, the framework is aware of the device's capabilities and the urgency of the task. We can now categorize updates by priority: Urgent: Typing, clicking, hovering (must be handled immediately). Transition: Navigating a page, filtering a list (can take a few hundred milliseconds). Background: Prefetching data, logging (can wait for idle time). By using Time Slicing, we ensure that the main thread never remains blocked for more than a few milliseconds. This effectively eliminates "Jank" on low-end devices. As an architect, you aren't just optimizing for speed; you are optimizing for responsiveness, ensuring that the interface feels fluid regardless of the computational load happening in the background. • Tip: Concurrent rendering isn't about making rendering faster; it's about making it interruptible. Use tools like useTransition in React to wrap heavy non-urgent state updates, keeping your high-priority interactions buttery smooth. #WebArchitecture #ConcurrentRendering #ReactFiber #Javascript #FrontendPerformance #UbisageCodes #ObaidAshiq
To view or add a comment, sign in
-
-
✨Just finished building a modern, glassmorphic calculator using the classic trio: HTML, CSS, and JavaScript! 🧮✨ I wanted to push my front-end skills by combining clean logic with a polished UI. This project helped me dive deeper into: CSS Glassmorphism: Using backdrop-filter and transparency for that "frosted glass" look. JavaScript Logic: Handling calculations, state management for inputs, and DOM manipulation. Responsive Design: Ensuring the UI stays crisp across different screen sizes. There’s something so satisfying about turning lines of code into a functional, tactile tool. Check out the video below to see it in action! Hashtags: #WebDevelopment #Javascript #Frontend #CSS #CodingProject #Portfolio #Glassmorphism #WebDesign
To view or add a comment, sign in
-
𝗛𝘆𝗱𝗿𝗮𝘁𝗶𝗼𝗻 & 𝗙𝘂𝗹𝗹 𝗛𝘆𝗱𝗿𝗮𝘁𝗶𝗼𝗻 In the quest for SEO and fast initial paints, we use Server-Side Rendering (SSR). But SSR only sends the "dead" HTML. Hydration is the process where the client-side JavaScript "wakes up" that HTML, attaching event listeners and establishing the state that makes the page interactive. • The Crux: Think of SSR as delivering a high-definition photograph of a car. It looks great immediately, but you can’t drive it. Full Hydration is the process of building the entire engine after the car has been delivered. Until the engine is fully assembled (the JS is downloaded, parsed, and executed), the user is stuck in the "Uncanny Valley"—they see a button, but clicking it does absolutely nothing. • The Deep Insight (Architect's Perspective): The industry often obsesses over LCP (Largest Contentful Paint), but for complex SPAs, the real killer is TBT (Total Blocking Time) caused by Full Hydration. In a "Full Hydration" model, the reconciliation process is an all-or-nothing game. The browser’s main thread is held hostage while the framework builds a complete Virtual DOM tree to match the existing HTML. This "Rehydration Tax" scales linearly with the complexity of your DOM. If you have a 2,000-node tree, the user’s device must process 2,000 nodes before a single dropdown works. As architects, we must recognize that Full Hydration is a performance bottleneck by design. It treats the UI as a monolith. To scale, we must move toward "Resumability" or "Partial Hydration" (which we will cover in the next post). • Tip: If your Lighthouse score shows a massive gap between "First Contentful Paint" and "Time to Interactive," you aren't suffering from a slow network; you are suffering from a Hydration Heavyweight. #WebArchitecture #FrontendPerformance #React #Javascript #SoftwareEngineering #SSR #WebPerf
To view or add a comment, sign in
-
-
What Actually Happens When You Type a URL in Your Browser? Most developers use browsers every day. But few understand the engineering pipeline behind it. Here’s what happens in milliseconds. 1️⃣ DNS Lookup The browser finds the IP address of the website. 2️⃣ HTTP Request It sends a request to the server asking for the webpage. 3️⃣ Server Response The server returns HTML, CSS, JavaScript, and assets. 4️⃣ HTML Parsing → DOM Tree The browser converts HTML into a DOM structure. 5️⃣ CSS Parsing → CSSOM Tree CSS rules are converted into a style structure. 6️⃣ Render Tree Creation DOM + CSSOM combine to create the Render Tree. 7️⃣ Layout (Reflow) The browser calculates the size and position of elements. 8️⃣ Painting & Compositing Finally, the browser converts everything into pixels on the screen. All of this happens in milliseconds. Understanding this browser rendering pipeline helps developers build: • Faster websites • Better UI performance • Optimized frontend code • Improved web performance • Efficient JavaScript execution Great developers don’t just write code. They understand how the browser works internally. If you want to learn this concept in more depth, check out this video: 🎥 https://lnkd.in/g8Jh6QtC #hiteshchoudhary #WebDevelopment #FrontendDevelopment #BrowserEngineering #JavaScript #SoftwareEngineering #FullStackDeveloper #WebPerformance #Coding #Programming #TechEducation
To view or add a comment, sign in
-
-
I stopped writing px values in CSS. Every project I've worked on had the same problem — magic numbers everywhere. Padding: 24px. Margin: 16px. Gap: 12px. Why those numbers? Nobody remembers. Then the design team says "tighten the spacing" and you're doing find-and-replace across 40 files. Now I use one SCSS function: $base: 8px; @function space($n) { @return $base * $n; } .card { padding: space(3); // 24px margin: space(2); // 16px gap: space(1.5); // 12px } Tighten the whole UI? Change one number. Everything recalculates. This is one of the SCSS features most developers never touch. There are more — loops that generate 12 grid classes from 4 lines, maps that end z-index chaos, conditionals that auto-adjust line-height based on font size. I wrote a full breakdown with real examples. Link in the comments. What's your approach to spacing — design tokens, utility classes, or vibes? #frontend #css #scss #webdev
To view or add a comment, sign in
-
-
REACT INTERNALS - PART 4 What Actually Triggers a Re-render? In the previous parts, we saw: 1. Rendering recalculates UI 2. Reconciliation compares elements 3. Keys preserve identity Now the real question: When does React decide to render again? 🔥 The 4 Main Re-render Triggers 1️⃣ State Updates setCount(count + 1) When state changes, the component function runs again. Important detail: The component re-runs - not necessarily the entire DOM updating. Rendering ≠ DOM mutation. 2️⃣ Parent Re-renders If a parent component re-renders, its children re-render too. Unless they are memoized (React.memo) and their props are referentially stable. This is why component boundaries matter. 3️⃣ Props Reference Changes React compares props using shallow comparison. <Child config={{ theme: "dark" }} /> A new object is created on every render → new reference → child re-renders. Even if the values look identical. React compares references, not deep values. 4️⃣ Context Value Changes When a context value changes: All consuming components re-render. Even if they use only part of that value. Context widens the render scope. 🧠 Important Mental Model React re-renders when: 1. State changes 2. Parent renders 3. Props reference changes 4. Context updates React does not re-render when: 1. Variables change 2. You mutate objects silently 3. You update the DOM manually React responds to its own state system - not external mutations. 🎯 Why This Matters Performance issues usually aren’t caused by React. They’re caused by: 1. Poor state placement 2. Unstable references 3. Large render trees Understanding what triggers a re-render gives you control. And control is where performance architecture begins. #ReactJS #FrontendDevelopment #JavaScript #ReactInternals #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 I thought I understood the Intersection Observer API… until I looked under the hood. Like most frontend developers, I’ve used it for things like: • Lazy loading images • Infinite scrolling • Triggering animations when elements enter the viewport But today I spent some time digging deeper into how it actually works inside the browser, and it’s surprisingly elegant. Traditionally, many scroll-based implementations rely on listening to scroll events and repeatedly calculating element positions relative to the viewport. The issue is that this can run very frequently during scrolling, which may trigger layout calculations and impact performance. Intersection Observer approaches this differently. Instead of us constantly checking element visibility, the browser internally tracks intersections and notifies us only when specific thresholds are crossed. A few things that stood out to me: ⚡ Observers trigger only when visibility thresholds change ⚡ Multiple elements can share a single observer instance ⚡ The browser can batch and optimize intersection calculations internally It’s one of those APIs that feels simple on the surface but becomes really impressive when you look at the design behind it. Frontend engineering never stops surprising me 🌐 💬 What’s a Web API you explored recently that felt simple at first but turned out to be deeply engineered? #frontend #javascript #webperformance #webdevelopment #browser
To view or add a comment, sign in
-
Hey Everyone!! Day 24 of #30DaysCodingChallenge Today I built a Dark & Light Theme Toggle Web Application using HTML, CSS, and JavaScript. What I Built A responsive theme toggle application that allows users to switch between Light Mode and Dark Mode. The selected theme is saved in the browser, so it remains even after refreshing the page. Purpose of the Project The goal was to strengthen my understanding of DOM manipulation, CSS variables, and browser storage while building a practical real-world feature used in modern websites. Key Features ✔ Toggle between Dark and Light mode with a single button. ✔ Dynamic button text update (Dark ↔ Light). ✔ Smooth transition effect using CSS. ✔ Persistent theme using Local Storage (remains after refresh). ✔ Clean and centered UI using Flexbox. What I Learned 🔹 How `classList.toggle()` makes theme switching simple and efficient. 🔹 How to store user preferences using `localStorage`. 🔹 How to apply conditional rendering based on saved data. 🔹 Improved understanding of combining CSS and JavaScript for better UX. Building small UI features like theme toggles helps me understand how modern applications enhance user experience while keeping code clean and maintainable. #JavaScript #WebDevelopment #FrontendDeveloper #HTML #CSS #CodingChallenge #BuildInPublic
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