React.memo — The Most Misunderstood Performance Optimization in React Most developers think `React.memo` makes a component faster. It does not. `React.memo` does not make your component render faster. It stops React from rendering a component when nothing has changed. And that is a huge difference. Imagine this: function Parent() { const [count, setCount] = useState(0); return ( <> <button onClick={() => setCount(count + 1)}> Increment </button> <Child /> </> ); } function Child() { console.log("Child rendered"); return <h1>I never change</h1>; } Every time you click the button: * Parent re-renders * Child re-renders * Console logs again Even though `Child` never changed. That is wasted work. Now use `React.memo`: const Child = React.memo(function Child() { console.log("Child rendered"); return <h1>I never change</h1>; }); Now when the parent re-renders, React compares the previous props and new props of `Child`. If the props are the same, React skips rendering the component. That means: * Less rendering * Less work for React * Better performance in large apps What actually happens internally? `React.memo` does a shallow comparison. That means React checks: prevProps === nextProps For primitive values like: name="Durgesh" age={22} it usually works perfectly. But for objects and functions: <Child user={{ name: "Durgesh" }} /> This will STILL re-render. Because every render creates a new object reference. Same problem with functions: <Child onClick={() => console.log("Hello")} /> That function is recreated every render. So `React.memo` thinks the props changed. Which means your optimization fails. This will NOT work const Child = React.memo(({ user }) => { console.log("Rendered"); return <h1>{user.name}</h1>; }); <Child user={{ name: "Durgesh" }} /> Because `user` is a new object every render. This WILL work const user = useMemo(() => ({ name: "Durgesh" }), []); <Child user={user} /> Now the object reference stays the same. So `React.memo` can skip the render. When should you use React.memo? Use it when: * The component renders often * The component is expensive to render * The props rarely change * You have large lists or complex UI When should you NOT use it? Do NOT wrap every component with `React.memo`. Because `React.memo` also has a cost. React now has to compare props every render. For tiny components, that comparison may cost more than simply rendering. The biggest mistake developers make is this: They use `React.memo` everywhere without checking if the component was actually re-rendering unnecessarily. First use React DevTools Profiler. Measure. Then optimize. Because performance optimization is not about adding more code. It is about stopping useless work. And that is exactly what `React.memo` does. #react #reactjs #javascript #frontend #webdevelopment #performance
React.memo Performance Optimization in React
More Relevant Posts
-
Web UI development might have just fundamentally changed. I just caught up on the latest Code Report, and Changlu (former React core team & Midjourney engineer) dropped something massive: Pretext. If you've ever built a text-heavy UI - like a virtualized list or a masonry layout - you know the classic performance bottleneck. Every time the browser needs to figure out how tall a paragraph is, it triggers a layout reflow. This is historically one of the most expensive operations a browser can perform. Pretext is a fast, accurate, and comprehensive text measurement library written in pure TypeScript that completely bypasses this issue. Here is why it is such a foundational shift: Zero DOM Reflows: It utilizes the Canvas API to calculate the exact pixel width of any string outside the DOM. Custom Line-Break Logic: It accurately calculates height by handling the complex line-break rules across all browsers and languages. Clean API: You simply use prepare to cache segment widths and layout to instantly get the total height and line count. As someone working deep in the AI space, what fascinated me most was how Changlu solved the near-impossible task of writing that cross-browser line-break algorithm. He deployed AI models in a recursive testing loop - having them write the logic, test it against actual text in real browsers, compare the results, and refine it over weeks until it was perfectly solid. It is a brilliant example of applying AI to solve complex, deterministic infrastructure problems to build better developer tools. The browser doesn't have to own text measurement anymore. I highly recommend checking out Pretext if you are building data-heavy interfaces! #WebDevelopment #Frontend #TypeScript #ArtificialIntelligence #SoftwareEngineering #WebPerformance #DeveloperTools #Pretext
To view or add a comment, sign in
-
`setState()` Debunked: What *Really* Happens Under the Hood? 🤯 Ever wondered what magic `setState()` invokes behind the scenes in Flutter? It's more than just a UI refresh – it kicks off a fascinating process of dirty element tracking and rebuild scheduling. Many devs treat it like a black box, but understanding its inner workings is 🔑 to optimizing performance. So, what *actually* happens? 1. Marking Elements as Dirty: `setState()` doesn't directly rebuild your widget. Instead, it marks the associated `Element` as "dirty." Think of it like flagging that element needing an update. Flutter keeps track of all these "dirty" elements. 2. The `BuildOwner`: The Maestro of Rebuilds Enter the `BuildOwner`. This class is responsible for orchestrating the build process. After `setState()` marks an element dirty, the `BuildOwner` is notified that something needs to be rebuilt. 3. Scheduling the Rebuild: The `BuildOwner` doesn't immediately trigger a rebuild. It politely asks the `SchedulerBinding` to schedule a frame. This ensures that all rebuilds happen in a coordinated manner, typically during the next frame rendering. ⚡️ 4. The Rebuild Phase: When the frame is rendered, the `BuildOwner` walks through the tree of dirty elements. For each dirty element, it calls the `build()` method of the corresponding widget, creating a new widget subtree. 5. Diffing and Updating: Flutter then compares the new widget subtree with the existing one, efficiently updating only the parts of the UI that have changed. This diffing process is crucial for performance. What developers often miss: 🤔 * `setState()` calls can be coalesced. Multiple `setState()` calls within the same frame will typically result in a single rebuild, preventing unnecessary work. * Not *everything* rebuilds. Flutter's smart diffing algorithm ensures that only the affected parts of the UI are updated. * The further up the tree `setState()` is called, the larger portion of the UI will be marked dirty for rebuild. 🌳 * `setState` isn't synchronous. It schedules a rebuild for the next frame. This is why you sometimes see UI updates appear "delayed." Why does Flutter work this way? This asynchronous, batched approach is designed for performance. By scheduling rebuilds and diffing the widget tree, Flutter minimizes the amount of work needed to update the UI, resulting in smoother animations and better responsiveness. Real-world consequences: Understanding this process helps you: ✓ Debug redundant rebuilds. Use the Flutter DevTools to identify widgets that are rebuilding unnecessarily. ✓ Optimize state management. Avoid calling `setState()` high up in the widget tree if only a small part of the UI needs to be updated. ✓ Predict UI update behavior. Knowing that `setState()` is asynchronous helps you avoid common pitfalls, such as relying on UI changes to be immediately reflected. #Flutter #Dart #FlutterDevelopment #FlutterTips #MobileDevelopment
To view or add a comment, sign in
-
Bundle size is not an engineering metric. It's a UX metric. Every kilobyte your user downloads is time spent waiting instead of using your app. Here's how to fix it 👇 The browser downloads your JavaScript, parses it, compiles it, then executes it. A 1MB bundle costs 1MB of download plus hundreds of milliseconds of parse and compile time. On a mid-range Android device that's seconds before anything is interactive. Find what's in your bundle first. Use bundlephobia.com before installing any package. Use webpack-bundle-analyzer or Vite's rollup-plugin-visualizer to see what's inside. Most teams are shocked — unknown libraries, duplicate dependencies, massive packages used for one function. Code splitting is the highest impact change. Split at the route level first — home page users shouldn't download settings page code. Then split heavy components that only appear in certain flows. Tree shaking means paying only for what you use. import { debounce } from 'lodash-es' ships one function. import _ from 'lodash' ships the entire library. Replace heavy libraries. date-fns instead of moment — 70% smaller. nanoid instead of uuid — 90% smaller. Native fetch instead of axios — zero bytes. Your bundle size is a bill your users pay on every visit. Optimize it like you're spending their money — because you are. Repost for your team ♻️ ───────────────────────── حجم الـ bundle مش metric هندسى ده metric لتجربة المستخدم. كل كيلوبايت بيتحملها المستخدم هو وقت في الانتظار بدل ما يستخدم التطبيق. إزاي تصلحه 👇 المتصفح بيحمل الـ JavaScript، parse، compile، execute. ملف 1MB بيكلف 1MB تحميل زائد مئات الـ milliseconds. على موبايل متوسط ده ثواني قبل ما أي حاجة تشتغل. اعرف إيه اللي جوه الـ bundle. استخدم bundlephobia.com قبل أي package. استخدم webpack-bundle-analyzer أو rollup-plugin-visualizer في Vite. معظم الفرق بتتفاجأ — مكتبات مجهولة، dependencies متكررة، packages ضخمة لفانكشن واحدة. Code splitting أعلى تأثير. قسّم على مستوى الـ routes الأول. بعدين قسّم الكومبوننتات التقيلة اللي بتظهر في flows معينة بس. Tree shaking يعني بتدفع على اللي بتستخدمه بس. import { debounce } from 'lodash-es' بتبعت فانكشن واحدة. import _ from 'lodash' بتبعت المكتبة كلها. استبدل المكتبات التقيلة. date-fns بدل moment — 70% أصغر. nanoid بدل uuid — 90% أصغر. fetch النيتف بدل axios — صفر بايت. حجم الـ bundle فاتورة مستخدمينك بيدفعوها في كل زيارة. حسّنه وكأنك بتصرف فلوسهم — لأنك فعلاً كده. شاركه مع فريقك ♻️ #WebPerformance #JavaScript #FrontendDevelopment #WebDev #CoreWebVitals #أداء_الويب #تطوير_الويب
To view or add a comment, sign in
-
-
A React component re-renders when state or props change. It also re-renders when its parent re-renders. That second one is where most performance bugs hide. On a trading dashboard updating 10 times per second, every wasted render is a dropped frame. Users notice. The app feels sluggish. And the fix isn't "rewrite it" — it's understanding three hooks and when to actually reach for them. The memoization toolkit in React is useMemo, useCallback, and React.memo. Most devs know what they do. Fewer know when not to use them. USEMEMO — CACHE AN EXPENSIVE COMPUTATION const processedData = useMemo(() => rawTrades.filter(t => t.volume > 1000).sort(...), [rawTrades] // only recomputes when rawTrades changes ) Use this when the derivation is genuinely expensive — sorting, filtering, or aggregating large datasets. Don't use it to memoize a string concatenation. The cache itself has a cost. USECALLBACK — STABLE FUNCTION REFERENCE FOR CHILD PROPS const handleSelect = useCallback((id: string) => { setSelected(id) }, []) // same reference across renders = child won't re-render Without this, a new function is created every render. If that function is passed as a prop to a memoized child, it breaks the memo — the child sees a "changed" prop and re-renders anyway. REACT.MEMO — SKIP RENDER IF PROPS HAVEN'T CHANGED const TradeRow = memo(({ trade }: { trade: Trade }) => { return <tr>{trade.symbol}</tr> }) Only works when the props are stable. If you're passing a new object or function reference on every render, memo does nothing — you need useMemo and useCallback upstream first. Here's the answer pattern that lands well in interviews: "I'd profile first with React DevTools to confirm which components are actually re-rendering unnecessarily. Then I'd stabilise callback references with useCallback, memoize expensive derivations with useMemo, and wrap pure display components with React.memo. Memoization is a last resort — not a default — because it adds overhead. The profiler tells you where that overhead is justified." The word "profile" is doing a lot of work in that answer. It signals that you don't guess at performance problems — you measure them. That's what separates the senior answer from the junior one. The trap interviewers set: "So should I just wrap everything in memo?" The correct answer is no — and knowing why not is the whole point. What's the worst unnecessary re-render bug you've debugged? Drop it below 👇 #React #JavaScript #FrontendDevelopment #WebPerformance #SoftwareEngineering
To view or add a comment, sign in
-
-
I was filling a 6-step form yesterday. While I wan on step 5, Accidentally dragged the page. It refreshed. And gone back to step 1. Surprisingly all that data gone. As a frontend developer, my first thought was, a single localStorage call could have prevented this. But the better thought came right after. Here's what most devs reach for: localStorage.setItem("form_step", JSON.stringify(formData)) Simple. Works. Survives reloads, tab closes, even browser restarts. But if you want to build it properly, the real pattern is a custom hook: → useEffect watches formData and writes to localStorage on every change → On mount, read it back and restore exactly where the user left off → On successful submission, call localStorage.removeItem() to clean up That's it. 10 lines. Every multi-step form should have this by default. But here's where it gets more interesting: localStorage is synchronous and has no expiry. For a draft form, that's fine. But at scale, you might want: → sessionStorage: clears when tab closes, better for sensitive forms → IndexedDB: for large payloads or file data → A draft API endpoint: if you need cross-device restore The right tool depends on one question: "How long and where should this data survive?" Most apps never ask it. They either lose the user's progress entirely or store it forever with no cleanup. A refreshed page should never cost a user their work. That's not a nice-to-have. That's just good UX. #Frontend #React #JavaScript #WebDevelopment #UX #UIEngineering #Webdeveloper #UI #Form #Validation #Development
To view or add a comment, sign in
-
-
Built a Finance Dashboard using React 💸 It helps track income and expenses in a simple, clean way while visualizing financial insights. 🔧 Tech Stack: React (Hooks), Tailwind CSS, Recharts, React Icons, LocalStorage ⚙️ Key Features: • Add, edit, delete transactions • Search & filter by category/type • Admin & Viewer role system • Dark mode 🌙 • Data persistence using localStorage (no data loss on refresh) • Summary cards (balance, income, expenses, top category) • Pie chart for spending insights • Line chart for monthly balance trend • Fully mobile responsive 💡 React Concepts Used: • useState for managing UI & transaction state • useEffect for syncing data with localStorage • Conditional rendering (modals, roles, dark mode) • Derived state (filtered data, totals, charts) • Component-driven UI thinking 📊 Libraries Used: • Recharts → for Pie & Line charts • React Icons → for UI icons • Tailwind CSS → for fast and responsive styling 🚧 Challenges I Faced: Managing and transforming raw transaction data into meaningful insights (monthly trends & category breakdown) was tricky. 👉 Solved it by creating custom data maps (like monthlyDataMap & categoryMap) and then converting them into chart-friendly formats. Also handled edge cases like editing transactions, maintaining unique IDs, and keeping UI state consistent. 🎯 Tried to keep the UI minimal, fast, and user-friendly. Here’s the live demo 👇 https://lnkd.in/gpHQay68 Would love your feedback 🙌 #reactjs #frontend #webdevelopment #javascript #tailwindcss #projects
To view or add a comment, sign in
-
As a Frontend Lead, I often see confusion around React's state management. Let's break down a common one: why React state updates don't always feel immediate. THE GLITCH: Imagine a user clicks a button to toggle a feature. They see the button change state instantly, but the actual UI element it controls flickers or takes a noticeable moment to update. This inconsistency is frustrating and makes the app feel sluggish. THE ROOT CAUSE: React's state updates are asynchronous. When you call setState (or the setter from useState), React doesn't immediately re-render the component. Instead, it schedules a re-render for a later time. This batching of updates is a performance optimization, but it can lead to that perceived lag if not handled correctly. The UI might be showing the old state while React is preparing to render the new state. THE FIX: The key is understanding React's rendering cycle and ensuring your UI logic uses the most up-to-date state. Immediate Feedback: For simple toggles or visual indicators, you can often update the UI optimistically* before React has even processed the state change. useEffect for Side Effects: When your UI update depends on the actual new state being rendered, use useEffect. This hook runs after* the component has rendered with the new state. Here's a quick example using useState: import React, { useState, useEffect } from 'react'; function MyComponent() { const [isActive, setIsActive] = useState(false); const [displayState, setDisplayState] = useState('Inactive'); const handleClick = () => { // Optimistic update for immediate UI feedback on the button itself setIsActive(!isActive); // This will be handled by useEffect }; useEffect(() => { // This runs after the component has re-rendered with the new 'isActive' state setDisplayState(isActive ? 'Active' : 'Inactive'); }, [isActive]); // Dependency array ensures this runs when 'isActive' changes return ( <div> <button onClick={handleClick}> {isActive ? 'Deactivate' : 'Activate'} </button> <p>Current Status: {displayState}</p> </div> ); } By separating the immediate button feedback from the rendering of the dependent UI element via useEffect, you ensure a smoother user experience. #ReactJS #Frontend #WebDev
To view or add a comment, sign in
-
-
Ever found yourself deep in a React project, hunting for that one specific Button component variation, only to realize you’ve rebuilt it three times? Or worse, you change a global theme setting and accidentally break the layout on a page you haven't looked at in weeks? If you’re building with React and Material UI (MUI), there’s a better way to work. Enter Storybook. The Problem: The "Context" Headache 🧠 Developing UI components inside a massive app is hard. You often have to: Login and navigate through five screens just to see a specific Modal state. Wrestle with complex API data just to test a "Loading" spinner. Guess how a component looks in "Dark Mode" without switching the entire app's theme. The Solution: Component-Driven Development 🛠️ Storybook acts as a "sandbox" or a "workshop" that lives alongside your app. It allows you to build, view, and test your React components in total isolation. +1 When paired with MUI, Storybook becomes your living design system. It allows you to: Isolate Logic: Build a complex MUI DataGrid without worrying about your app's Redux state or Auth providers. Document Variations: Create "Stories" for every state—Primary, Secondary, Error, Success, or Disabled. Visual Regression Testing: See exactly how a theme change in your createTheme() affects every single component instantly. How it Works in Practice 💻 The Setup: You install Storybook in your React project. It runs on a separate port (usually 6006). The Story: You write a .stories.tsx file for your component. The Interaction: Using the Controls Addon, you can toggle MUI props (like variant="contained" or color="secondary") using a visual UI, without touching the code. // Example: Button.stories.tsx import { Button } from '@mui/material'; export default { title: 'Components/MyButton', component: Button, }; export const Primary = () => ( <Button variant="contained" color="primary"> Click Me </Button> ); Why Your Team Will Thank You 🙌 For Developers: Faster iterations. No more "refresh and navigate" loops. For Designers: A shared source of truth. Designers can jump into Storybook to verify that the MUI implementation matches the Figma specs. For New Hires: It’s an interactive manual. Instead of digging through src/components, they can browse the Storybook library to see what's already built. Are you using Storybook in your current workflow? Or are you still building components the "hard way" inside the main app? Let’s talk in the comments! 👇 #ReactJS #MaterialUI #Storybook #WebDevelopment #Frontend #DesignSystems #ProgrammingTips
To view or add a comment, sign in
-
Still writing long, complex class components just to manage simple UI logic? 🤔 Or wondering why most modern React code looks completely different? That shift is because of 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀. 🚀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 — 𝗧𝗵𝗲 𝗠𝗼𝗱𝗲𝗿𝗻 𝗪𝗮𝘆 𝘁𝗼 𝗪𝗿𝗶𝘁𝗲 𝗥𝗲𝗮𝗰𝘁 Earlier, React relied heavily on class-based components. 👉 But now, 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 are the standard. They are simpler, cleaner, and easier to manage. 💡 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 (𝗮𝗻𝗱 𝘄𝗵𝘆 𝘂𝘀𝗲 𝘁𝗵𝗲𝗺)? A Functional Component is just a 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 that returns JSX. With the introduction of 𝗛𝗼𝗼𝗸𝘀, they can now: ◦ Manage state ◦ Handle side effects ◦ Replace almost everything class components did 👉 Why developers prefer them: ◦ Less boilerplate ◦ Easier to read and test ◦ Better for modern React patterns 🔍 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁 𝘄𝗶𝘁𝗵 𝗦𝘁𝗮𝘁𝗲 𝑖𝑚𝑝𝑜𝑟𝑡 { 𝑢𝑠𝑒𝑆𝑡𝑎𝑡𝑒 } 𝑓𝑟𝑜𝑚 "𝑟𝑒𝑎𝑐𝑡"; 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝐶𝑜𝑢𝑛𝑡𝑒𝑟() { 𝑐𝑜𝑛𝑠𝑡 [𝑐𝑜𝑢𝑛𝑡, 𝑠𝑒𝑡𝐶𝑜𝑢𝑛𝑡] = 𝑢𝑠𝑒𝑆𝑡𝑎𝑡𝑒(0); 𝑟𝑒𝑡𝑢𝑟𝑛 ( <𝑑𝑖𝑣> <ℎ2>𝐶𝑜𝑢𝑛𝑡: {𝑐𝑜𝑢𝑛𝑡}</ℎ2> <𝑏𝑢𝑡𝑡𝑜𝑛 𝑜𝑛𝐶𝑙𝑖𝑐𝑘={() => 𝑠𝑒𝑡𝐶𝑜𝑢𝑛𝑡(𝑐𝑜𝑢𝑛𝑡 + 1)}> 𝐼𝑛𝑐𝑟𝑒𝑚𝑒𝑛𝑡 </𝑏𝑢𝑡𝑡𝑜𝑛> </𝑑𝑖𝑣> ); } 𝑒𝑥𝑝𝑜𝑟𝑡 𝑑𝑒𝑓𝑎𝑢𝑙𝑡 𝐶𝑜𝑢𝑛𝑡𝑒𝑟; 🧠 𝗪𝗵𝗮𝘁’𝘀 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴 𝗵𝗲𝗿𝗲? ◦ Counter is a function acting as a component ◦ useState adds state inside a function ◦ When count updates → UI re-renders automatically 👉 No this, no lifecycle confusion 👉 Just simple, predictable functions 🏗️ 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 Functional components are used in almost every modern React app: ◦ Building reusable UI components (buttons, cards) ◦ Handling form inputs and user interactions ◦ Fetching and displaying API data ◦ Managing UI state in dashboards and admin panels 👉 Combined with hooks, they power full applications 📌 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ✔ Functional Components are the modern standard in React ✔ Hooks make them powerful enough to replace class components ✔ Simpler syntax → better readability and maintainability If you're still using class components… it's probably time to switch. 💬 Are you fully using functional components, or still working with class components in your projects? 💡 Part of my #FrontendRevisionMarathon — breaking down Frontend concepts daily 🚀 🚀 Follow Shubham Kumar Raj for more such content. #ReactJS #JavaScript #WebDevelopment #Frontend #CodingTips #100DaysOfCode #codinginterview #learnjavascript #programming #interviewprep #CareerGrowth #SowftwareEngineering #OpenToWork #FrontendDevelopment #Coding #Hiring
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