Nobody talks about this React performance trap — and it bit me hard in production. I was using useContext to manage auth + theme + cart state in a mid-size app. Only a few components actually used the cart state. But every time the cart updated — every single component consuming the context re-rendered. Even the ones that only needed the user's name. Here's why: React's Context API re-renders all consumers whenever the context value reference changes — regardless of which slice of state they actually use. There are workarounds with Context: → Split into multiple contexts (AuthContext, CartContext, ThemeContext separately) → Wrap consumers in React.memo() → Use useMemo to stabilize the context value But honestly? All of these feel like duct tape. This is exactly where Zustand and Redux Toolkit shine. Both let you subscribe to only the slice of state you need. A component using useSelector(state => state.user.name) will only re-render when that specific value changes — not when the cart updates, not when the theme toggles. ZUSTAND Minimal boilerplate, great for small-to-mid apps. Selector-based subscriptions built in. REDUX TOOLKIT Structured, scalable. useSelector memoizes out of the box with Reselect. The lesson I took away: useContext is great for low-frequency, global state (auth, theme, locale). The moment you have state that changes often and is consumed by many components — reach for a proper state manager. Performance issues in React are rarely obvious until they're in production. Knowing why re-renders happen matters more than memorizing which hook to use. Have you run into this? Would love to hear how you solved it — Context splitting, Zustand, RTK, or something else entirely? #ReactJS #JavaScript #WebDevelopment #Frontend #Zustand #Redux
React Performance Trap: useContext Re-renders All Consumers
More Relevant Posts
-
🪝: Our app was slow. Users were complaining. Here's the 5 things that fixed it (and the 1 thing that almost made it worse). Performance optimisation is one of those things that sounds abstract until you have actual users complaining. Here's what I've done in real projects that actually moved the needle: 1. CODE SPLITTING with React.lazy() → Don't load the whole app on first visit → Lazy load routes and heavy components → Real impact: cut initial load time by ~40% on a large project 2. MEMOISATION — but only where it matters → React.memo() for components that receive the same props often → useMemo() for expensive calculations → useCallback() for functions passed as props → WARNING: Over-memoising adds overhead. Profile first, optimise second. 3. OPTIMISED RENDER CYCLES → Identify what's causing unnecessary re-renders (React DevTools Profiler is your best friend) → Move state as close to where it's used as possible → Avoid storing derived data in state — calculate it 4. IMAGE OPTIMISATION → Lazy load images below the fold → Use appropriate formats (WebP where possible) → Set explicit width/height to avoid layout shifts 5. BUNDLE ANALYSIS → Use webpack-bundle-analyzer or Vite's rollup-plugin-visualizer → You'll be shocked what's in your bundle sometimes The thing that almost made it worse? Premature memoisation everywhere. We wrapped every component in React.memo before profiling. It actually slowed things down. MEASURE. THEN OPTIMISE. What's your go-to performance trick? #ReactJS #PerformanceOptimisation #FrontendDev #JavaScript #WebPerformance #CodeSplitting #ReactHooks
To view or add a comment, sign in
-
⚛️ Zustand — A Clean & Minimal Approach to State Management in React When building applications with React, one thing that really impacts code quality over time is how you manage state. There are plenty of options out there, but Zustand stands out for keeping things simple without sacrificing flexibility. 🧠 What is Zustand? Zustand is a lightweight state management library that lets you manage global state with very little setup. 👉 No providers 👉 No reducers 👉 No heavy boilerplate It keeps things straightforward and easy to reason about. ⚡ How it works At its core, Zustand is just a simple store: import { create } from "zustand"; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })); And you can use it anywhere in your app: const count = useStore((state) => state.count); const increment = useStore((state) => state.increment); No extra wrapping or complex setup needed. 🔥 Why Zustand works well ✔ Clean and minimal API ✔ Updates only what actually changes (better performance) ✔ No need to wrap your entire app ✔ Helps you move faster with less code ⚠️ Where to be cautious Zustand is great, but it’s not a one-size-fits-all solution. 👉 For large-scale apps with complex workflows 👉 When you need strict structure or advanced debugging tools you might want something more opinionated. 💡 Practical perspective Zustand fits really well when: ✔ Your app is small to medium in size ✔ You want to keep things simple ✔ You don’t need heavy state architecture 🚀 Final thought State management doesn’t have to be complicated. Sometimes, keeping things simple is the best decision you can make for your codebase. ❓ What are you using in your projects — Redux or Zustand? 📌 I’ll share a detailed comparison of Redux vs Zustand in my next post. #reactjs #zustand #redux #frontenddevelopment #javascript #webdevelopment #softwareengineering #fullstackdeveloper #dotnetfullstackdeveloper #react
To view or add a comment, sign in
-
-
I used to think I understood React… until I had to pass the same state through 3–4 components just to control one small thing 😅 It worked, but it didn’t feel right. So instead of jumping to another tutorial, I tried to actually "understand the problem" and that led me to the Context API. To keep things simple, I built a tiny “bulb toggle” app 💡 At first, everything was prop-based. Then I switched to Context… and the difference was obvious. Now: 1. I’m not passing props through unnecessary layers 2. Components feel more independent 3. The code is easier to read and reason about But I also learned something important while doing this: 👉 Context is helpful, but it’s not a replacement for everything If the state is simple and only needed in a few places, props are still totally fine. Context starts to make sense when multiple parts of your app need the same data. Still early in my journey, but this was one of those small moments where things started to click. If you’ve worked with Context before -> 👉 how do you decide between props, Context, or other state tools? #learninginpublic #reactjs #webdevelopment #javascript #frontenddevelopment
To view or add a comment, sign in
-
-
Your React App is Slow… and You Might Be the Reason Most developers use useMemo and React.memo but very few actually understand when NOT to use them ⚠️ I recently debugged a performance issue in a React dashboard. Everything looked optimized — but still, the UI was lagging. The reason? 👉 Memoization was used… but used wrongly. ⚡ Let’s break it down simply: 🔹 useMemo — Caches Calculations Use it when you have expensive computations Example: const filteredData = useMemo(() => { return data.filter(item => item.active); }, [data]); ✔ Prevents unnecessary recalculations ❌ Useless for cheap operations 🔹 React.memo — Stops Re-renders Wrap your component to avoid re-render when props don’t change const Card = React.memo(({ item }) => { return <div>{item.name}</div>; }); ✔ Great for large lists / heavy UI ❌ Useless if props change every render 🔥 The Real Problem Most people do this: Wrap everything in React.memo Add useMemo everywhere Hope performance improves 👉 Result: More complexity, same performance (sometimes worse) 💡 What Actually Works ✔ Use useMemo only for heavy calculations ✔ Use React.memo only when re-renders are costly ✔ Avoid passing new object/array references every render ✔ Measure performance before optimizing 🧠 The Mindset Shift Optimization is not about adding hooks It’s about removing unnecessary work 🚀 Final Takeaway Don’t optimize blindly. First understand: Why is it re-rendering? Is it actually slow? Then use the right tool. 👇 Curious — have you ever faced unnecessary re-renders in your app? #ReactJS #FrontendDevelopment #JavaScript #WebPerformance #ReactHooks #SoftwareEngineering #CleanCode #DevTips
To view or add a comment, sign in
-
-
Your React app feels slow, and you have no idea why. The truth is, it is probably re-rendering 10x more than it should be. React core philosophy is that UI is a function of state. When state changes, React re-evaluates the component tree. But if you are not careful, a single state change at the top of your tree can trigger a massive wave of unnecessary re-renders all the way down to the bottom. Here are the 3 most common reasons your React app is re-rendering too much: 1. Passing new object references in props. If you pass an inline object or function like style={{ color: 'red' }} or onClick={() => doSomething()}, React sees a brand new reference on every single render. Even if the contents are identical, React thinks the prop changed. 2. State lifted too high. If you have a form input that updates on every keystroke, and its state lives in a parent component alongside heavy data tables, typing one letter re-renders the entire table. 3. Missing memoization. Complex calculations or heavy child components that do not depend on the changed state will still re-render by default. React is fast, but it is not magic. Example: Instead of passing inline functions like this: <Button onClick={() => handleSubmit()} /> Use useCallback to keep the reference stable: const handleSubmit = useCallback(() => { ... }, []); <Button onClick={handleSubmit} /> Key takeaways: - Keep state as close to where it is used as possible. - Use memo for expensive child components. - Use useMemo and useCallback to preserve reference equality for objects and functions passed as props. #reactjs #webdevelopment #frontend #javascript #performance #softwareengineering #coding #webdev #reactdeveloper #programming
To view or add a comment, sign in
-
-
Today everything started to feel… more real. React Masterclass (Day 5). I began with: • Sharing state between components • Passing functions as props • Understanding how React handles state updates But instead of stopping there, I asked: How would this actually work in a real app? 💰 So I built a Budget Tracker: • Set initial balance • Add expenses that reduce it in real-time • Dynamic UI based on current state • Data persisted using localStorage • Clean updates using functional state 💡 Key concepts that clicked: • Lazy initialization (run logic only once) • Functional updates (state based on previous state) • Derived values (calculating remaining balance) Small concepts → Real product thinking. #React #Frontend #WebDevelopment #LearningInPublic #JavaScript
To view or add a comment, sign in
-
🚀React Bundle Analysis & Optimization Your React app might look fine… But if your bundle is heavy, users will feel the slowdown ⚠️ Let’s break this down simply 👇 🧩 What is a Bundle? 👉 When you build a React app, all your code + libraries are combined into JavaScript files (bundles) 💡 Example: • React • UI libraries • Utility functions ➡️ All packed into one or multiple JS files ⚠️ Why Large Bundles Are a Problem ❌ Slow initial load ❌ More JavaScript to execute ❌ Poor performance on low-end devices 👉 Bigger bundle = Slower app 🔍 What is Bundle Analysis? 👉 It helps you understand: • Which library is heavy • What is increasing bundle size • Where optimization is needed 📊 Tools give a visual breakdown of your bundle 🛠️ Tools You Can Use ✔ webpack-bundle-analyzer ✔ source-map-explorer 👉 Shows which dependency is taking the most space ⚡ How to Optimize Bundle 🧩 1. Code Splitting → Break bundle into smaller chunks ⚡ 2. Lazy Loading → Load components only when needed 🌳 3. Tree Shaking → Remove unused code automatically 📦 4. Dynamic Imports → Load heavy modules on demand 🧹 5. Remove Heavy Libraries → Replace with lighter alternatives 🔥 Real Impact ✔ Faster load time ✔ Better performance ✔ Improved user experience ✔ Smaller bundle size 🧠 Simple Way to Understand • Without Optimization → Big bundle → Slow app ❌ • With Optimization → Small chunks → Fast app ✅ 💬 Have you ever checked what’s inside your bundle? #React #WebPerformance #Frontend #JavaScript #WebDevelopment #Optimization #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
🔴90% of React applications have performance issues... and most developers don't even realize it. that might sound surprising but it's true. React is fast but it isn't automatically optimized. optimization is your responsibility. so what actually makes a React app slow? the reasons vary but the root cause is almost always the same: unnecessary re-renders. React's main task is to make sure your UI is up to date with your state and when your state changes, it should update the UI. That's normal, right? That's React doing its job. The problem is when it updates UI components that weren't even affected by the state change. think about it You have a parent component with state and inside it, there are 10 child components and only one of them was affected by your state change. But React? it re-renders all 10 of them that's exactly where performance dies. 📌So what actually solves this problem? 🔸React.Memo: it's like saying to React, "Hey, man, only update this component if its own props changed." 🔸useMemo: to remember results of heavy computations, so it doesn't compute it every time it renders۔ 🔸useCallback: to stop functions from being recreated, which would then make your child components re-render. but❗ and this is an important but don't use these tools blindly... first, use React DevTools Profiler to see if it's actually an issue۔ and then optimize۔ optimizing prematurely is like adding complexity without any real benefit. the secret to React performance is simple: move your state to the right place, and only update what needs updating🚀 how do you measure performance in your React applications? 👇 #ReactJS #WebDevelopment #MERNStack #JavaScript #Frontend #Performance #SoftwareEngineering #CodingTips #TechCommunity
To view or add a comment, sign in
-
-
Your React app isn't slow. Your folder structure is just a mess. When a React project grows, the "group by file type" approach breaks down. Putting all components in one folder, hooks in another, and utils somewhere else is a recipe for disaster. You end up scrolling through hundreds of files just to fix one bug. Here is how you structure a large React project for scale. Stop grouping by file type. Start grouping by feature. A feature-based architecture means everything related to a specific part of your app lives together. If you are working on the authentication flow, you should not have to leave the auth folder. Inside your src directory, structure it like this: src/ features/ auth/ components/ hooks/ services/ auth.slice.ts index.ts shared/ components/ Button.tsx hooks/ useClickOutside.ts utils/ formatDate.ts app/ store.ts router.tsx Why this works better: 1. High Cohesion Everything a feature needs is in one place. No more jumping between 5 different directories to understand a single workflow. 2. Strict Boundaries Features should not reach into other features' internals. Use an index.ts file to explicitly export only what is necessary. 3. Easier Onboarding New developers can look at the features folder and immediately understand what the application actually does. When a feature gets too complex, it naturally splits into smaller features. This scales infinitely better than the traditional flat structure. #reactjs #javascript #webdevelopment #frontend #softwareengineering #coding #architecture #cleancode #webdev #reactdeveloper
To view or add a comment, sign in
-
-
🚀 Just launched: react-state-vitals A zero-config memory & render monitor for React apps. While working on production apps, I kept asking: 👉 Why is this component re-rendering so much? 👉 Which store is growing in memory? 👉 Where is my performance actually going? So I built a tool to make this visible — instantly. 🧠 react-state-vitals gives you a live floating panel in development: • 📊 Store size tracking (Zustand, Context, React Query) • 🔁 Re-render counts per component • 🧬 JS heap usage insights • ⚡ Zero setup — just install and see Think of it as: 👉 “Vitals for your React state & memory” 📦 Try it here: https://lnkd.in/gU692hyT 🔥 Next I’m planning: • DevTools-like overlay • Identify memory-heavy components in real time • Visual performance timeline Would love feedback from fellow devs 🙌 What would you want this to track next? #React #JavaScript #Frontend #WebPerformance #OpenSource #NextJS #Zustand
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
Context can be optimized to avoid those re-renders, but at that point, you're basically building a DIY state manager. I’d rather just use Zustand and get selectors for free. Why fight the tool when you can just use one built for the job