Most developers go their entire careers without touching 'getSnapshotBeforeUpdate'. It is the niche lifecycle method that sits in the quiet space between the render phase and the actual DOM update. But when you need it, nothing else quite works the same way. The classic application is managing scroll positions in a chat window or a news feed. If you are adding new messages to the top of a list, the browser might naturally jump the scroll. You need to know exactly where the scroll bar was sitting before the new content arrived so you can adjust the scroll position in 'componentDidUpdate'. This method allows you to capture that exact DOM state and pass it forward. Why is it so specific? This method has a direct line to the DOM right before it changes. It allows you to 'capture' a snapshot, like a scroll offset, a cursor position, or a specific element size and pass it as a third argument to the next lifecycle stage. It is the only place where you can safely read from the DOM knowing the browser hasn't repainted yet, which prevents that annoying UI flicker. In the world of Hooks, we often try to replicate this logic with 'useLayoutEffect', but 'getSnapshotBeforeUpdate' remains the most explicit way to handle the pre-commit phase in class-based architectures. It is built for those specialized UI synchronization tasks where the physical state of the DOM matters just as much as the data in your state. #ReactJS #SoftwareEngineering #WebDevelopment #FrontendArchitecture #Javascript #CodingTips
Prathamesh P. Sakhare’s Post
More Relevant Posts
-
𝟵𝟵% 𝗼𝗳 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘀𝘁𝗿𝘂𝗴𝗴𝗹𝗲 𝘄𝗶𝘁𝗵 𝘁𝗵𝗲𝘀𝗲 𝗳𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 👇 Not because they’re hard… But because we rarely revisit the “why” behind the tools we use daily. 1️⃣ Before Flexbox & Grid — how were responsive layouts actually built in CSS? 2️⃣ 𝗦𝗖𝗦𝗦 vs 𝗣𝗼𝘀𝘁𝗖𝗦𝗦 — what’s the real difference? And is SCSS still relevant in 𝟮𝟬𝟮𝟲? 3️⃣ Can you explain the 𝟳-𝗶𝗻-𝟭 SCSS architecture? What exactly are partials? 4️⃣ What does an async function return in JavaScript? Write the exact syntax. 5️⃣ Which asset formats are most optimal for modern HTML rendering (especially with srcset)? 6️⃣ What is a 𝗖𝗗𝗡 — and why are 𝗖𝗗𝗡 links usually placed inside <𝗵𝗲𝗮𝗱>. What breaks if you move them to <𝗯𝗼𝗱𝘆>? 7️⃣ Which CSS unit scales most effectively across different viewport sizes—and why? If you can confidently answer all of these, you’re already ahead of most developers in real-world frontend engineering. Curious — how many can you answer without Internet? 👀 ~ Aslam Mohammed #frontend #javascript #webdevelopment #css #reactjs #frontenddeveloper #webperf #programming #softwareengineering #devcommunity #100DaysOfCode #techcareers
To view or add a comment, sign in
-
🚀 JavaScript Project 3: Counter System Built a stste-driven counter with increment, decrement and reset actions —but this time, I focused on how engineers think, not just making it work. 🔑 Key ideas: • State is the single source of truth • UI updates are centralized ( updateUI ) • Event delegation for scalable interaction • Data-driven actions using data-* attributes • Clear UI feedback (disabled states, interaction response) 💡Biggest insight: Don't manipulate the UI directly — update state, then let the UI reflect it. 🔗 Live: https://lnkd.in/dTNy6A2M 💻 Code: https://lnkd.in/dp638D6h This is part of my journey building JavaScript systems step-by-step. More coming. #JavaScript #Frontend #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Why does your 'ref' return 'null' the moment you wrap your input in a custom component? It is one of those React quirks that trips up even experienced developers. By default, refs do not behave like props. They are treated as special instances that stop at the component boundary to protect encapsulation. This is exactly why we need 'forwardRef'. It acts as a bridge that allows a parent component to reach through a child and grab a direct handle on an internal DOM node. The most practical application is building a reusable UI library. If you create a custom 'Input' or 'Button' component, your parent component might need to call '.focus()' or '.scrollIntoView()'. Without 'forwardRef', your parent is just holding a reference to a React internal object, not the actual HTML element. Another real-world scenario involves Higher-Order Components (HOCs). If you wrap a component with a 'withAnalytics' or 'withTheme' wrapper, that wrapper will 'swallow' the ref by default. By using 'forwardRef' in your HOC implementation, you ensure the reference passes through the wrapper and lands on the component that actually needs it. It is about making your abstractions transparent and ensuring that the parent component maintains the control it expects over the physical DOM. Using this pattern sparingly is key. It is an escape hatch for those moments where declarative state isn't enough to manage physical browser behavior. It keeps your component interfaces clean while providing the necessary access for specialized UI interactions. #ReactJS #SoftwareEngineering #Frontend #WebDevelopment #Javascript #CodingTips #CodingBestPractices
To view or add a comment, sign in
-
There’s something interesting about working with Next.js in real-world projects — the benefits don’t always show up in documentation, but they become obvious once things go into production. One noticeable shift is how performance starts improving without constant manual optimization. Features like Server Components quietly reduce client-side load, which reflects directly in smoother user interactions. Routing and layouts also feel more structured. Instead of managing scattered logic, the project naturally moves toward a cleaner architecture, especially as it scales. Another practical observation is with Incremental Static Regeneration (ISR). It helps keep content fresh without sacrificing speed — something that used to require custom solutions before. On the development side, iteration feels faster. Changes reflect quickly, debugging becomes simpler, and overall friction reduces during builds. But the real difference shows up in consistency — fewer performance issues, better load times, and a more stable user experience over time. Next.js doesn’t feel like just another framework in the stack anymore. It starts influencing how applications are designed from the ground up. Curious — what changes have you noticed after using Next.js in actual projects? #NextJS #FrontendDevelopment #WebPerformance #JavaScript #TechInsights
To view or add a comment, sign in
-
-
🤔 Ever had a page feel frozen even though your code was still running? That can happen when the event loop is so busy that other tasks do not get a chance to run. 🧠 JavaScript interview question What is event loop starvation? ✅ Answer Event loop starvation happens when some code keeps the event loop so busy that other queued work gets delayed. It usually happens in two ways: • long synchronous code blocks the main thread • microtasks keep running before the loop can move to the next task 🔍 A bit more detail JavaScript runs on a single main thread for most frontend work. After each task, the engine clears the microtask queue before moving to the next task. So starvation can happen when: • a heavy synchronous task blocks everything • microtasks keep extending themselves and delay macrotasks like setTimeout Example 1: microtask starvation setTimeout(() => console.log("timer fired"), 0); let count = 0; function starve() { Promise.resolve().then(() => { count++; if (count < 100000) { starve(); } }); } starve(); The timer is ready, but it cannot run until the microtask queue fully drains. --- Example 2: synchronous blocking function longComputation() { const start = Date.now(); while (Date.now() - start < 5000) { // block the main thread } } console.log("start"); setTimeout(() => { console.log("timeout fired"); }, 0); longComputation(); console.log("end"); Even though the timer is scheduled with 0, it still cannot run until the long synchronous task finishes, because the main thread is blocked. ⚠️ Important clarification Starvation is not just about timers. It can delay: • UI updates • user input • rendering • network callback handling That is why the page can feel frozen even though nothing crashed. 🛠️ How to avoid it • break heavy work into smaller chunks • avoid recursively flooding the microtask queue • yield with setTimeout when appropriate • use requestIdleCallback for low priority work • move CPU heavy work to a Web Worker #javascript #webdevelopment #frontend #webperf #interviewprep
To view or add a comment, sign in
-
I’ve used CSS-in-JS heavily in production systems. At small scale, it feels like a clear win scoped styles, dynamic props, no naming headaches. It improves developer experience in all the right ways. But at scale, the conversation changes. CSS-in-JS moves work into the runtime: -Styles are generated during render -Injected into the DOM repeatedly -Paid for during hydration, not build Individually, these costs look small. Together, they show up as slower renders, heavier pages, and harder to debug performance issues. What makes this tricky is that nothing “breaks.” The system just becomes gradually less efficient. That’s why many teams are quietly shifting, towards build-time extraction, utility first CSS, or zero runtime approaches. Not because CSS-in-JS is wrong but because the cost model doesn’t scale cleanly. As engineers, we don’t just choose tools based on DX. We choose them based on where the cost lands. And in this case, the cost lands on the user. Curious — at what scale did CSS-in-JS start becoming a problem for you? #FrontendEngineering #WebPerformance #SoftwareEngineering #CleanCode #ScalableSystems #JavaScript #ReactJS #CSS
To view or add a comment, sign in
-
My list UI was behaving weirdly… items were changing unexpectedly 😅 Yes, seriously. At first, I thought it was a state issue. But the problem was something very simple. 💡 I was doing this: {items.map((item, index) => ( Seemed fine… right? ❌ ⚠️ This caused: • Wrong UI updates • Items swapping incorrectly • Hard-to-debug bugs 💡 Then I fixed it: 👉 Used a unique and stable key 🧠 Example: {items.map((item) => ( ✅ Result: • Correct UI updates • No unexpected behavior • Predictable rendering 🔥 What I learned: Keys are not just for React warnings 👉 they control how React updates the UI 💬 Curious: Do you still use index as key… or avoid it? #ReactJS #FrontendDeveloper #JavaScript #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Your useEffect is firing 6 times. It's probably not what's in the dependency array. I had [options] in mine. One dependency. Looked fine. The effect ran on every single render anyway — hammering my API with duplicate calls I couldn't explain. The problem wasn't the value. It was the reference. options was an object getting recreated fresh on every render, so React saw a "new" dependency every time — even when the actual data hadn't changed. React doesn't deep-compare objects in the dep array. It checks identity. Fix was wrapping options in useMemo. Two lines. Effect ran once. Done. But honestly, the bigger shift was realising I'd been thinking about dependencies wrong. It's not just what is in the array — it's whether the things in the array are actually stable between renders. If your effect fires more than it should, check the stability of your deps, not just the list. What kills you about useEffect? Curious if this one's common. #react #javascript #reacthooks #frontenddevelopment #webdev
To view or add a comment, sign in
-
-
We often hear that JavaScript is single threaded. But at the same time, it handles API calls, timers, and UI updates smoothly. The reason is the Event Loop. Here is a simple way to understand it. Think in terms of 5 parts: 1. Call Stack This is where code runs right now. If something blocks here (like an infinite loop), everything else stops. 2. Web APIs The browser handles things like fetch, setTimeout, and events outside the main thread. When they are done, they send callbacks to queues. 3. Microtask Queue (high priority) This includes Promise callbacks and async/await. All microtasks run completely before anything else happens. -> If you keep adding microtasks (like recursive Promise.then), you can actually block rendering completely. 4. Macrotask Queue (low priority) This includes setTimeout, setInterval, and other tasks. Only one macrotask runs at a time. 5. Render After microtasks are done, the browser updates the UI (layout and paint). -> The browser decides when to paint — not strictly after every loop. Simple cycle: Run one macrotask → run all microtasks → update UI → repeat JavaScript isn’t non-blocking — the event loop just makes it feel that way. #javascript #frontend #reactjs #webdevelopment #softwareengineering #webperformance #systemdesign #Coding
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