🧠 Why React.memo Sometimes Doesn’t Work You wrap your component: const Child = React.memo(({ data }) => { console.log("Rendered"); return <div>{data}</div>; }); You expect it to not re-render. But it still does. Why? 🔍 The real reason React.memo does shallow comparison. So if you pass this 👇 <Child data={{ value: count }} /> 👉 That object is new on every render Even if count didn’t change. ⚠️ Result React sees: {} !== {} 👉 “Props changed” → re-render happens ✅ Fix Memoize the object: const memoData = useMemo(() => { return { value: count }; }, [count]); <Child data={memoData} /> Now the reference stays stable. 🎯 Real Insight React.memo doesn’t prevent re-renders. It only skips them when props are the same reference. 💥 Senior takeaway Most “optimization” fails because of unstable references, not logic. 🧠 Why React.memo Sometimes Doesn’t Work You wrap your component: const Child = React.memo(({ data }) => { console.log("Rendered"); return <div>{data}</div>; }); You expect it to not re-render. But it still does. Why? 🔍 The real reason React.memo does shallow comparison. So if you pass this 👇 <Child data={{ value: count }} /> 👉 That object is new on every render Even if count didn’t change. ⚠️ Result React sees: {} !== {} 👉 “Props changed” → re-render happens ✅ Fix Memoize the object: const memoData = useMemo(() => { return { value: count }; }, [count]); <Child data={memoData} /> Now the reference stays stable. 🎯 Real Insight React.memo doesn’t prevent re-renders. It only skips them when props are the same reference. 💥 Senior takeaway Most “optimization” fails because of unstable references, not logic. #ReactJS #FrontendDeveloper #JavaScript #WebPerformance #SoftwareEngineering #CodingTips #TechCareers #LearningInPublic
Durga Prasad’s Post
More Relevant Posts
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
To view or add a comment, sign in
-
> **Stop guessing where your files go. Here's the React folder structure every developer needs to know. 🗂️** > > After years of messy codebases, late-night debugging sessions, and onboarding nightmares — the secret to a scalable frontend isn't just your code. It's **how you organize it.** > > Here's what each folder does and why it matters: > 📡 **API** — All your backend connections in one place. No more hunting for fetch calls. > 🎨 **Assets** — Static files, images, fonts. Clean and centralized. > 🧩 **Components** — Reusable UI building blocks. Write once, use everywhere. > 🌐 **Context** — Global state without prop drilling chaos. > 📦 **Data** — Static JSON content and constants. > 🪝 **Hooks** — Custom logic extracted and reusable across the entire app. > 📄 **Pages** — One folder per route. Clean, readable, scalable. > 🔄 **Redux** — Advanced state management for complex apps. > ⚙️ **Services** — Business logic and frontend services, separated from UI. > 🛠️ **Utils** — Helper functions that every file in your app will thank you for. > > A well-structured project isn't a luxury — **it's what separates junior from senior developers.** > > Save this. Share it with your team. Your future self will thank you. 💾 > > --- > 💬 What does YOUR folder structure look like? Drop it in the comments 👇 --- `#ReactJS` `#FrontendDevelopment` `#WebDevelopment` `#JavaScript` `#CleanCode` `#SoftwareEngineering` `#Programming` `#React` `#CodeNewbie` `#100DaysOfCode` `#FolderStructure` `#TechTips` `#DeveloperLife` `#SoftwareDeveloper` `#LearnToCode` `#OpenSource` `#CodingTips` `#FullStackDeveloper` `#FrontendEngineer` `#UIUXDevelopment` --- **Why this will go viral:** - Opens with a **pain point** every developer feels - Uses **emojis** for scanability on mobile - Ends with a **call to action** (comment + share) that boosts LinkedIn's algorithm - Mix of **broad** (`#WebDevelopment`) and **niche** (`#FolderStructure`) hashtags for maximum reach
To view or add a comment, sign in
-
-
> **Stop guessing where your files go. Here's the React folder structure every developer needs to know. 🗂️** > > After years of messy codebases, late-night debugging sessions, and onboarding nightmares — the secret to a scalable frontend isn't just your code. It's **how you organize it.** > > Here's what each folder does and why it matters: > 📡 **API** — All your backend connections in one place. No more hunting for fetch calls. > 🎨 **Assets** — Static files, images, fonts. Clean and centralized. > 🧩 **Components** — Reusable UI building blocks. Write once, use everywhere. > 🌐 **Context** — Global state without prop drilling chaos. > 📦 **Data** — Static JSON content and constants. > 🪝 **Hooks** — Custom logic extracted and reusable across the entire app. > 📄 **Pages** — One folder per route. Clean, readable, scalable. > 🔄 **Redux** — Advanced state management for complex apps. > ⚙️ **Services** — Business logic and frontend services, separated from UI. > 🛠️ **Utils** — Helper functions that every file in your app will thank you for. > > A well-structured project isn't a luxury — **it's what separates junior from senior developers.** > > Save this. Share it with your team. Your future self will thank you. 💾 > > --- > 💬 What does YOUR folder structure look like? Drop it in the comments 👇 --- **🔥 Hashtags:** `#ReactJS` `#FrontendDevelopment` `#WebDevelopment` `#JavaScript` `#CleanCode` `#SoftwareEngineering` `#Programming` `#React` `#CodeNewbie` `#100DaysOfCode` `#FolderStructure` `#TechTips` `#DeveloperLife` `#SoftwareDeveloper` `#LearnToCode` `#OpenSource` `#CodingTips` `#FullStackDeveloper` `#FrontendEngineer` `#UIUXDevelopment` --- **Why this will go viral:** - Opens with a **pain point** every developer feels - Uses **emojis** for scanability on mobile - Ends with a **call to action** (comment + share) that boosts LinkedIn's algorithm - Mix of **broad** (`#WebDevelopment`) and **niche** (`#FolderStructure`) hashtags for maximum reach
To view or add a comment, sign in
-
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐒𝐭𝐚𝐥𝐞 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐁𝐮𝐠 🚨 Many developers use useEffect daily… but get confused when bugs appear unexpectedly. Question: Why does this code log the wrong value? Example 👇 import React, { useState, useEffect } from "react"; export default function App() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } What’s the issue? 🤔 Even after clicking the button, console always logs: 0 Why? Because of stale closure. useEffect runs only once (empty dependency array []) and the interval callback captures the initial value of count (0). So it never sees updated state. Correct solution ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); Best practice ⭐ Use useRef to always get latest value without re-running effect import React, { useState, useEffect, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const countRef = useRef(count); useEffect(() => { countRef.current = count; }, [count]); useEffect(() => { const id = setInterval(() => { console.log(countRef.current); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } Tip for Interview ⚠️ Always be careful with dependency arrays in useEffect. Wrong dependencies can lead to stale data bugs. Good developers fix bugs. Great developers understand why they happen. #ReactJS #useEffect #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱. So how does your UI stay responsive while a fetch() is running? Most devs say "async/await". That's not an answer. That's a keyword. Here's what actually happens. 👇 ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗿𝗮𝗰𝗲 𝗮 𝘀𝗶𝗻𝗴𝗹𝗲 𝗳𝗲𝘁𝗰𝗵() 𝗰𝗮𝗹𝗹 𝘁𝗵𝗿𝗼𝘂𝗴𝗵 𝘁𝗵𝗲 𝗲𝗻𝘁𝗶𝗿𝗲 𝗲𝗻𝗴𝗶𝗻𝗲: 𝗦𝘁𝗲𝗽 𝟭 — fetch() hits the Call Stack. The JS engine sees it, pushes it on the stack. But fetch() is not pure JS — it's a Web API. 𝗦𝘁𝗲𝗽 𝟮 — The Call Stack offloads it to the Web API layer. The network request leaves JavaScript entirely. Your browser (or Node.js libuv) handles it in a separate thread. The Call Stack is now FREE. UI stays responsive. 𝗦𝘁𝗲𝗽 𝟯 — Response arrives. Callback enters the Task Queue. The Web API layer puts your .then() or await callback into the appropriate queue and waits. 𝗦𝘁𝗲𝗽 𝟰 — The Event Loop checks both queues. Microtask Queue first (Promise.then, MutationObserver). Drain it completely. Then take ONE callback from the Task Queue. 𝗦𝘁𝗲𝗽 𝟱 — Callback pushed onto the Call Stack. Executed. Your data is now in your component. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗽𝗮𝗿𝘁 𝗺𝗼𝘀𝘁 𝗱𝗲𝘃𝘀 𝗺𝗶𝘀𝘀: "Non-blocking" doesn't mean JavaScript runs in parallel. It means the blocking work is delegated to something that CAN run in parallel — Web APIs, OS threads, libuv. JavaScript itself never leaves the single thread. The illusion of concurrency comes from the queue system. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆: → A long synchronous loop BLOCKS your UI (it holds the Call Stack and the Event Loop never runs) → An awaited fetch() does NOT block your UI (it's off the Call Stack within microseconds) → CPU-heavy work should go in a Web Worker (move it off the main thread entirely) ━━━━━━━━━━━━━━━━━━━━━━━ The whiteboard above shows the full flow visually. Save it + this explanation as a pair. 📌 Interview question: "Is JavaScript asynchronous?" Correct answer: No — it's single-threaded and synchronous. Async behavior comes from the runtime environment around it. Drop a 🔥 if this clicked for you today. #JavaScript #FrontendDevelopment #ReactJS #NodeJS #SoftwareEngineering #OpenToWork #ImmediateJoiner
To view or add a comment, sign in
-
-
React Performance Tip: Stop Overusing useEffect — Use useQuery Instead One mistake I often see (and made myself earlier) while working with React apps is overusing useEffect for API calls. 👉 Typical approach: Call API inside useEffect Manage loading state manually Handle errors separately Re-fetch logic becomes messy This works… but it doesn’t scale well. 🔁 Better approach: Use React Query (useQuery) When I started using useQuery, it simplified a lot of things: ✅ Automatic caching ✅ Built-in loading & error states ✅ Background refetching ✅ Cleaner and more readable code 👉 Example: Instead of this 👇 useEffect(() => { setLoading(true); axios.get('/api/data') .then(res => setData(res.data)) .catch(err => setError(err)) .finally(() => setLoading(false)); }, []); Use this 👇 const { data, isLoading, error } = useQuery({ queryKey: ['data'], queryFn: () => axios.get('/api/data').then(res => res.data), }); 🔥 Result: Less boilerplate Better performance (thanks to caching) Easier state management 📌 Takeaway: If you're building scalable React applications, tools like React Query are not optional anymore — they’re essential. What’s one React optimization you swear by? Drop it in the comments 👇 #ReactJS #WebDevelopment #Frontend #JavaScript #SoftwareEngineering #CleanCode #TechTips #Developers
To view or add a comment, sign in
-
Day 92 of 2026 🧠 While everyone is arguing over Vercel's controversial new edge-compute pricing model dropped this morning, I’m focused on code that doesn't rack up a $10,000 server bill. I used to think modern JavaScript was completely memory-leak proof. I was wrong. Status: The Memory Sweep 🧹 I built a real-time dashboard that looked flawless for the first 10 minutes. But if a user left the tab open during their lunch break, their browser would freeze, the memory usage would spike to 2GB, and the app would crash. The garbage collector couldn't save me because I was holding onto data forever. I deployed the "Memory Sweep" Protocol: ⏱️ 1. The Uncleared Interval I used `setInterval` to fetch new data every 5 seconds. The Fix: When the user navigates away from that component, the interval keeps firing in the background forever. Always return a cleanup function (`clearInterval`) inside your `useEffect` or lifecycle unmount to destroy the timer. 👂 2. The Ghost Listeners I attached an event listener (`window.addEventListener('scroll', handleScroll)`) to trigger animations. The Fix: If you don't explicitly call `removeEventListener` when the component unmounts, the browser creates a duplicate listener every single time the user visits the page. Hundreds of ghost listeners will crash the tab. 🧟 3. Zombie Closures I stored large datasets in global variables outside my functions. The Fix: Functions in JavaScript retain access to their outer scope (closures). If a temporary function captures a massive 50MB array and never gets dereferenced, that 50MB is permanently trapped in RAM. Keep data scope as localized as possible. ----- Resource 📚 👉 Chrome DevTools Memory Inspector: Stop guessing why your app is slow. Take a verifiable "Heap Snapshot" before and after a user action. This built-in tool literally highlights the exact detached DOM nodes and arrays causing your memory leaks. (Creator: Paul Irish) ----- 👇 Devs, what is the sneakiest performance killer? A: Uncleared intervals and timeouts B: Duplicate event listeners attached to the window C: Massive un-optimized images Powered by: 🧠 Mindset: Performance Engineering ⚡ Protocol: The Memory Sweep #WebDevelopment #JavaScript #ReactJS #SoftwareEngineering #Founders #BuildInPublic #Day92 : Avinash
To view or add a comment, sign in
-
🚀 React Hooks: The Game-Changer Every Developer Must Master If you're working with React and still relying heavily on class components… it's time to level up. React Hooks completely transformed how we build components — making code cleaner, reusable, and easier to manage. Let’s break it down in a way that actually makes sense 👇 🔥 What are React Hooks? Hooks are special functions introduced in React 16.8 that allow you to use state and lifecycle features in functional components. 👉 No more bulky classes 👉 No more confusing this keyword 👉 Just clean, readable functions 🧠 Why Hooks Matter? ✔ Simplifies component logic ✔ Promotes code reuse ✔ Improves readability ✔ Makes testing easier ✔ Reduces boilerplate code ⚡ Most Important Hooks You Should Know 1. 🟢 useState Manages state inside functional components. JavaScript const [count, setCount] = useState(0); 👉 Perfect for counters, forms, toggles 2. 🔵 useEffect Handles side effects like API calls, subscriptions, DOM updates. JavaScript useEffect(() => { console.log("Component mounted"); }, []); 👉 Think of it as componentDidMount + componentDidUpdate + componentWillUnmount 3. 🟣 useContext Avoids prop drilling by sharing data globally. 👉 Great for themes, auth, user data 4. 🟡 useRef Access DOM elements or persist values without re-render. JavaScript const inputRef = useRef(); 5. 🔴 useMemo & useCallback Optimize performance by memoizing values and functions. 👉 Prevent unnecessary re-renders 👉 Crucial for large-scale apps 💡 Pro Tips (From Real Projects) ✅ Don’t overuse useEffect — keep dependencies clean ✅ Use useMemo only when performance actually matters ✅ Break complex logic into custom hooks ✅ Follow naming convention: useSomething() 🚀 Custom Hooks = Real Power You can create your own hooks to reuse logic: JavaScript function useFetch(url) { // reusable logic } 👉 This is where senior-level React starts 💯 ⚠️ Common Mistakes to Avoid ❌ Calling hooks inside loops/conditions ❌ Ignoring dependency array in useEffect ❌ Over-optimizing with memoization ❌ Mixing too much logic in one component 🏁 Final Thought React Hooks are not just a feature — they are a mindset shift. If you truly master hooks, you move from writing code ➝ to designing scalable front-end systems. 💬 Want React + .NET Interview Questions & Real Project Scenarios? Comment "HOOKS" and I’ll share 🚀 🔖 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #Coding #SoftwareDevelopment #TechLearning #Developers #100DaysOfCode #Programming #ReactDeveloper #AngularVsReact #DotNet #FullStackDeveloper
To view or add a comment, sign in
-
-
🚀 Fetch vs Axios in JavaScript When building modern web applications, interacting with APIs is a daily task. Two of the most commonly used tools for this are Fetch and Axios. 🔹 What is fetch()? Definition: fetch() is a built-in Web API in JavaScript used to make HTTP requests to servers and retrieve resources. 👉 It is promise-based and available in all modern browsers. 📌 How Fetch Works >> Sends a request to a server (GET, POST, etc.) >> Returns a Promise >> Resolves to a Response object >> You must extract data manually (e.g., .json()) 💻 Example async function fetchData() { try { const response = await fetch("https://lnkd.in/dQeGAVaB"); // Checking response status manually if (!response.ok) { throw new Error("HTTP error! Status: " + response.status); } // Convert response into JSON const data = await response.json(); console.log(data); } catch (error) { console.error("Fetch Error:", error); } } ⚠️ Important Characteristics of Fetch ✔️ Built into browser (no installation) ✔️ Returns Promise ✔️ Requires manual JSON parsing ✔️ Does NOT throw errors for HTTP failures (you must handle it) ✔️ Slightly more verbose 🔹 What is axios? Definition: axios is a third-party JavaScript library used to make HTTP requests from the browser or Node.js. 👉 It is also promise-based but provides many additional features out of the box. 📌 How Axios Works >> Sends HTTP requests (GET, POST, PUT, DELETE, etc.) >> Automatically transforms response into JSON >> Automatically throws errors for bad status codes >> Provides advanced configuration options 💻 Example import axios from "axios"; async function fetchData() { try { const response = await axios.get("https://lnkd.in/dQeGAVaB"); // Axios directly gives data console.log(response.data); } catch (error) { console.error("Axios Error:", error); } } ⚠️ Important Characteristics of Axios ✔️ Requires installation (npm install axios) ✔️ Automatic JSON transformation ✔️ Better error handling ✔️ Supports interceptors (modify request/response globally) ✔️ Supports timeout, cancellation, headers easily ✔️ Cleaner and shorter syntax 💡 When to Use Fetch vs Axios? 👉 Use Fetch when: >> You want a lightweight solution >> No external dependencies required >> Working on small/simple projects 👉 Use Axios when: >> You are building real-world applications >> Need better error handling >> Want features like: >>Interceptors, Global configuration, Request cancellation #JavaScript #WebDevelopment #Axios #FetchAPI #Frontend #Programming #Developers #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