Most developers use `useMemo()` because they heard it improves performance. But here’s the truth: `useMemo` is not for making your app “faster” magically. It is for avoiding unnecessary work. Imagine your component renders again and again because some state changes. Every render means: * functions run again * calculations run again * arrays/objects get recreated again And sometimes that becomes expensive. Example: You have a list of 10,000 products and you are filtering or sorting them on every render. Without `useMemo`, even if only a button color changes, the filtering logic runs again. const filteredProducts = products.filter(product => product.price > 1000 ) Now imagine this runs on every render. That is unnecessary work. With `useMemo`: const filteredProducts = useMemo(() => { return products.filter(product => product.price > 1000) }, [products]) Now React stores the previous result and only recalculates when `products` changes. That stored value is called memoization. Memoization = remembering the previous result so you don’t have to calculate it again. Why use `useMemo`? ✅ Prevent expensive calculations from running again ✅ Avoid unnecessary re-renders in child components ✅ Improve performance when dealing with large lists, sorting, filtering, heavy computations What problem does it solve? Without `useMemo`: * Slow UI * Lag while typing/searching * Heavy calculations on every render * Child components re-render because new object/array references are created. So if you pass it to a child component, React thinks it changed every time. const user = useMemo(() => ({ name: "Durgesh" }), []) Now the reference stays the same. But there’s a catch 👇 Do NOT use `useMemo` everywhere. `useMemo` itself has a cost. For simple calculations, just write normal code. Rule of thumb: 👉 Use `useMemo` only when: * the calculation is expensive * the value is passed to memoized child components * re-rendering is causing performance issues Don’t optimize first. Measure first. Then optimize. That’s what good React developers do. #react #javascript #webdevelopment #frontend #reactjs #useMemo #performance #coding
Why Use useMemo in React for Performance Optimization
More Relevant Posts
-
Most developers use `useMemo()` because they heard it improves performance. But here’s the truth: `useMemo` is not for making your app “faster” magically. It is for avoiding unnecessary work. Imagine your component renders again and again because some state changes. Every render means: * functions run again * calculations run again * arrays/objects get recreated again And sometimes that becomes expensive. Example: You have a list of 10,000 products and you are filtering or sorting them on every render. Without `useMemo`, even if only a button color changes, the filtering logic runs again. const filteredProducts = products.filter(product => product.price > 1000 ) Now imagine this runs on every render. That is unnecessary work. With `useMemo`: const filteredProducts = useMemo(() => { return products.filter(product => product.price > 1000) }, [products]) Now React stores the previous result and only recalculates when `products` changes. That stored value is called memoization. Memoization = remembering the previous result so you don’t have to calculate it again. Why use `useMemo`? ✅ Prevent expensive calculations from running again ✅ Avoid unnecessary re-renders in child components ✅ Improve performance when dealing with large lists, sorting, filtering, heavy computations What problem does it solve? Without `useMemo`: * Slow UI * Lag while typing/searching * Heavy calculations on every render * Child components re-render because new object/array references are created. So if you pass it to a child component, React thinks it changed every time. const user = useMemo(() => ({ name: "Durgesh" }), []) Now the reference stays the same. But there’s a catch 👇 Do NOT use `useMemo` everywhere. `useMemo` itself has a cost. For simple calculations, just write normal code. Rule of thumb: 👉 Use `useMemo` only when: * the calculation is expensive * the value is passed to memoized child components * re-rendering is causing performance issues Don’t optimize first. Measure first. Then optimize. That’s what good React developers do. #react #javascript #webdevelopment #frontend #reactjs #useMemo #performance #coding
To view or add a comment, sign in
-
-
Software Engineers reject hookup culture. Because it has: No labels. No rules. No commitment. They already have something that gives them all three. React Hooks. Labels. ✅ Rules. ✅ Commitment. ✅ Try to be casual with it And it'll crash your entire app. This is Post 7 of the series: 𝗥𝗲𝗮𝗰𝘁 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱 Where I explain what React is actually doing behind the scenes. Here's what's actually happening👇 React doesn't track your hooks by name. It tracks them by position. Every render, React walks an internal array. Index by index. Like a strict attendance register. Hook 1 → slot [0] ✅ Hook 2 → slot [1] ✅ Hook 3 → slot [2] ✅ That's the reason when you try to put a hook in an if statement, it gives you an error. function App({ isLoggedIn }) { const [name, setName] = 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲("") // index 0 if (isLoggedIn) { 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁(() => { ... }) // index 1 (sometimes! as isLoggedIn can be true or false) } const [age, setAge] = 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲(𝟬) // index 1 or 2 ?? } Because: Condition true → all 3 hooks run → slots filled correctly ✅ Condition false → Hook 2 is skipped → React reads age state where it expected useEffect ❌ Your app doesn't just break. It breaks wrong. Wrong values. Wrong renders. Wrong everything. This isn't a bug in React. This IS React. Each component has a Fiber node. That Fiber stores a linked list of hook states. React walks it in order... Every render, no exceptions. The rules of hooks aren't random. They exist because hooks are just an indexed array. Arrays don't care about your variable names. They only care about position. So next time someone asks why hooks have rules It's not React being dramatic. It's React being consistent. Follow Farhaan Shaikh if you want to understand React more deeply. 👉 Read the previous post: How useState works: https://lnkd.in/d7TvJb-W #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #BuildInPublic #ReactHooks #LearnInPublic #FrontendTips #WebDev #React
To view or add a comment, sign in
-
After learning React’s architecture, I was a bit confused about why everyone stresses “small bundle size”. Then it clicked: bundle size isn’t just a number in Webpack stats - it’s a direct UX lever. On mobile or slow networks, every extra KB adds download time + CPU work + battery drain. Studies in 2026 show ~100 KB of JavaScript can cost users about 1 second of interaction delay on average phones, because the bottleneck has shifted from “download” to “parse and execute”. This shows up as: 1. Slower Time to Interactive (TTI) 2. Poorer Core Web Vitals (LCP, INP) 3. Higher bounce rates, especially on mobile‑first markets. Here’s how we keep bundles lean in React apps: 1. Code splitting & React.lazy() – Split routes and heavy components so users only load what they actually use. Can cut 40–70% from the initial bundle. 2. Tree shaking + precise imports – Use ES modules and import only what you need (e.g., import { debounce } from 'lodash-es') instead of import *, which can reduce library payloads by 50–90%. 3. Minification, compression, and caching – Ship minified builds with gzip/Brotli, use hashed filenames, and chunk vendor code so it’s cached effectively. 4. Bundle audits & dependency hygiene – Analyze the bundle, spot heavy libraries, and replace/remove anything that doesn’t clearly justify its size. 5. Set budgets and monitor – Define bundle‑size limits in CI/CD and track Core Web Vitals so you can see the real‑world impact of each change. What techniques do you use to keep your JS bundles small in React apps? Have you ever cut a bundle by 30–50% and seen a clear UX win? #ReactNativePerfomance #WebPerformance #FrontendPerformance #BundleOptimization #JavaScript #WebDev #FrontendDevelopment #ReactJS #NextJS #MobilePerformance #CleanCode #ScalableFrontend #DeveloperExperience #TechWriting #BuildInPublic #SoftwareEngineering #PerformanceMatters #OptimizeEverything #DevTips #ProgrammingLife
To view or add a comment, sign in
-
Most JavaScript bugs aren’t “big” bugs. They’re small ones hiding in places like this: Trying to read a nested property that doesn’t exist. And suddenly: Cannot read properties of undefined One tiny operator that saves a lot of headaches: Optional chaining (?.) Instead of writing: user.company.address.city Write: user.company?.address?.city If something is missing, your app doesn’t crash. It just returns undefined. Small JS tip. Big difference in real projects. Do you use ?. everywhere already or still catch yourself forgetting it sometimes? #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CodingTips #ReactJS #TypeScript #Developers #AITechDaily
To view or add a comment, sign in
-
-
I recently completed a project focused on building and enhancing a Simple Todos app. This project was a great way to dive deeper into React state management, conditional rendering, and dynamic UI updates. Key features I implemented: ✅ Dynamic Task Creation: Added a text input and "Add" button to create tasks on the fly. ✅ Bulk Task Entry: Built a smart "Multi-Add" feature automatically generates three separate entries. ✅ In-Place Editing: Implemented an "Edit/Save" toggle for each item, allowing users to update titles without leaving the list. ✅ Task Completion: Added checkboxes with a persistent strike-through effect to track progress. ✅ Stateful Deletion: Ensured a smooth user experience when removing items from the list. This project pushed me to think about component structure, reusable props, and clean UI logic in React. Check out the implementation here: https://lnkd.in/dtG46cwU #Day97 #ReactJS #WebDevelopment #Frontend #JavaScript #CodingProject #LearnToCode #ReactComponents #NodeJS #ExpressJS #BackendDevelopment #WebDevelopment #NxtWave #LearningJourney #TechAchievement
To view or add a comment, sign in
-
-
We had a React page that kept getting slower over time. No obvious bug. Just gradual performance drop. Here’s what we found 👇 Problem: → Page slowed down after repeated navigation → Memory usage kept increasing Root cause: → Event listeners not cleaned up → setInterval running in background → useEffect cleanup missing What I did: → Added proper cleanup functions → Removed unnecessary subscriptions → Ensured effects were scoped correctly Result: → Stable performance → No memory growth → Better user experience Insight: React doesn’t manage side effects for you. If you don’t clean up… Your app pays the price later. #ReactJS #MemoryLeak #Frontend #SoftwareEngineering #CaseStudy #JavaScript #Debugging #WebDevelopment #Engineering #Performance #FrontendDeveloper
To view or add a comment, sign in
-
⚛️ Most React developers fix the symptom. Here's how to fix the cause. Stale closures in useState aren't a beginner mistake — they're a design decision you need to understand. This pattern silently breaks in production: const [filters, setFilters] = useState(initialFilters); useEffect(() => { const interval = setInterval(() => { fetchData(filters); // always reads initial filters // never the updated ones }, 3000); return () => clearInterval(interval); }, []); // empty deps = stale closure trap The fix most devs reach for: → Add filters to the dependency array → Now the interval resets every time filters change → Race conditions start appearing The actual fix: const filtersRef = useRef(filters); useEffect(() => { filtersRef.current = filters; }, [filters]); useEffect(() => { const interval = setInterval(() => { fetchData(filtersRef.current); // always fresh }, 3000); return () => clearInterval(interval); }, []); // stable interval, no race conditions 💡 What's happening under the hood: Every render creates a new closure. useRef gives you a mutable box that lives outside the render cycle — so your async callbacks always read the latest value without triggering re-renders. This is the difference between knowing React's API and understanding React's model. Have you run into stale closures in a production app? What was the context? #ReactJS #JavaScript #FrontendArchitecture #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
There's a page in the React docs called "You Might Not Need an Effect." I'd say it's one of the most important pages in the entire React documentation. And most developers have either never read it or read it once and moved on. The whole idea comes down to one question: is your code syncing React with something React doesn't control? A WebSocket, a browser API, a third-party library? If yes, useEffect makes sense. If no, you're probably just adding extra renders and making your code harder to follow. Some patterns worth knowing: If you're deriving a value from props or state, just calculate it during render. No state, no effect needed. If you're responding to a user action like a click or form submit, put it in the event handler. The event handler already knows what happened. The effect doesn't. If you need to reset state when a prop changes, use the key prop. React will remount the component and reset everything automatically. If you're chaining effects where one sets state and triggers another, collapse all of it into a single event handler. React batches those updates into one render. If a child is fetching data just to pass it up to a parent, flip the flow. Let the parent fetch and pass it down. The rule the docs give is honestly the clearest way I've seen it put: if something runs because the user did something, it belongs in an event handler. If it runs because the component appeared on screen, it belongs in an effect. Every unnecessary useEffect is an extra render pass, an extra place for bugs to hide, and more code for the next person to untangle. Worth a read if you haven't: https://lnkd.in/gqUr7e_S How many effects in your current codebase do you think would actually pass that test? #ReactJS #Frontend #JavaScript #WebDevelopment #CleanCode
To view or add a comment, sign in
-
Understanding your frontend folder structure is key to building maintainable applications! 🚀 This infographic breaks down a clean, scalable setup: 💻 src/: Your application source code. 🏗 components/: Reusable parts of your UI (e.g., buttons, forms). 🧩 pages/: The full layouts for different URL routes in your app. 🧠 redux/ or context/: Where you manage the global state of your application. 🪝 hooks/: Encapsulate reusable, stateful logic. 🌐 api/ & services/: Manage network requests and application logic. A solid structure keeps your codebase organized as your project grows. How do you organize your projects? Let me know in the comments! 👇 #frontend #webdevelopment #coding #reactjs #softwareengineering #fullstack #codeorganisation #ImmediateJoiner #Immediate #angular #javascript #typescript
To view or add a comment, sign in
-
-
Why React Apps Feel So Fast (Hint: It’s NOT the DOM) When I first started learning React, I thought: “It directly updates the DOM efficiently.” But that’s not the real magic. The real hero? → Virtual DOM Here’s how it works: 1️⃣ React creates a Virtual DOM (a lightweight copy of the real DOM) 2️⃣ When state changes, React creates a new Virtual DOM 3️⃣ It compares the old vs new (this is called diffing) 4️⃣ Only the changed parts are updated in the real DOM (reconciliation) Result: Instead of reloading the entire page, React updates ONLY what changed. Think of it like this: Imagine updating a document: Rewrite the whole file Just edit the changed lines React chooses the second approach Why this matters: • Better performance • Smoother UI updates • Scalable applications One thing I realized: React is not “fast because of DOM” It’s fast because it avoids unnecessary DOM work If you're learning frontend, understanding this concept changes how you think about UI updates. What was your “aha moment” while learning React? #React #WebDevelopment #Frontend #JavaScript #CodingJourney
To view or add a comment, sign in
More from this author
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