React patterns that often cause subtle bugs Some React code looks completely fine at first glance. But over time, certain patterns can cause confusing bugs or make the UI harder to reason about. Here are a few I try to watch out for 👇 1️⃣ Copying props into state const [user, setUser] = useState(props.user) This creates two sources of truth. If the parent updates props.user, the state inside the component may not update the way you expect. That’s how UI gets out of sync. 2️⃣ Storing values that can be derived Instead of storing: const [fullName, setFullName] = useState("") Sometimes you can simply calculate: const fullName = `${firstName} ${lastName}` Derived state often adds extra logic and unnecessary re-renders. 3️⃣ Lifting state higher than necessary Lifting state up is helpful when multiple components need the same data. But lifting it too high can lead to: • unnecessary re-renders • harder state management • tightly coupled components Sometimes the better answer is to keep state closer to where it is used. 4️⃣ Large components that do too many things When one component handles too much, it becomes harder to: • understand • test • debug Smaller, focused components are usually easier to work with. 5️⃣ Overusing useEffect A lot of logic ends up in useEffect when it does not need to be there. If something can be calculated directly from props or state, it often does not need an effect. None of these patterns are always wrong. But I’ve noticed many React bugs come from state being: • duplicated • misplaced • harder to reason about Keeping one clear source of truth usually makes the UI much easier to understand. What React pattern do you see most often that leads to bugs? #reactjs #frontend #javascript #webdevelopment #softwareengineering #reactdeveloper #reacthooks #frontendengineering
Common React Patterns That Cause Bugs
More Relevant Posts
-
🚀 Understanding React from First Principles Instead of jumping directly into hooks and libraries, I decided to step back and ask a simple question: 👉 What problem is React actually solving? At its core, React is not just a library — it’s a way of thinking about UI. 🔍 First Principles Breakdown: • UI = Function of State → The interface changes whenever the data changes • Manual DOM manipulation is inefficient → Traditional JS requires updating elements step-by-step • React solves this using abstraction → You describe what the UI should look like, not how to update it ⚙️ Core Mechanism: Components → Break UI into reusable pieces State → Stores dynamic data Virtual DOM → Efficiently compares changes Reconciliation → Updates only what’s necessary 💡 Insight: React shifts your mindset from "How do I update the UI?" to "What should the UI look like given this data?" This small shift is powerful. I’m currently learning React deeply by focusing on fundamentals and first-principles thinking — not just syntax. #React #Frontend #WebDevelopment #LearningInPublic #JavaScript #FirstPrinciples
To view or add a comment, sign in
-
Nobody expects to fail these 7 React questions. And then they do. The tricky part? None of them are about some lesser-known API. They test whether you actually understand how React works under the hood. Here's what catches people off guard: 🔴 setState batching — calling setCount(count + 1) three times doesn't give you 3. It gives you 1. Closures are sneaky. 🟡 useRef vs useState — mutating a ref updates the value, but the UI never knows. It just sits there. Stale. 🔵 Stale closures in useEffect — an empty dependency array + setInterval = a timer that's frozen in time. Forever stuck at 1. 🟢 React.memo shallow trap — you wrapped your component in memo, feeling smart. But you're passing a new object literal every render. Memo does nothing. 🟣 useEffect cleanup order — most devs think cleanup only runs on unmount. Wrong. It runs before every single re-render effect. Every. Time. 🟡 Index as key — it works until you sort, filter, or reorder. Then React maps the wrong DOM to the wrong data. Inputs keep stale values. Good luck debugging that. 🔴 State mutation — you pushed to the array and called setState. React compared references. Same ref = no update. Your UI is frozen and you have no idea why. I put all 7 into a carousel with code snippets, wrong answers, correct answers, and explanations. Swipe through and test yourself honestly. The pattern? The questions that trip people up aren't about syntax. They're about understanding how React actually thinks. Save this for your next interview — whether you're giving it or taking it. --- #react #javascript #frontend #interviewprep #webdevelopment #softwareengineering #reactjs
To view or add a comment, sign in
-
Most bugs in production don’t come from complex systems... 💻 They come from simple misunderstandings. Here’s one that even experienced developers occasionally get wrong 👇 🧠 Three snippets. Same intention. Different behavior. // 1 function logValue(value) { if (value === 2) return; console.log(value) } for (let i = 1; i < 5; i++) { logValue(i) } // 2 for (let i = 1; i < 5; i++) { if (i === 2) return; console.log(i) } // 3 [1,2,3,4].forEach((num) => { if (num === 2) return console.log(num) }) 🔍 What’s actually happening? Snippet 1 → Safe abstraction return exits only the function Loop continues Output: 1, 3, 4 Snippet 2 → Dangerous assumption return exits the entire enclosing function Loop stops completely at 2 Output: 1 👉 If this is inside a React component or handler → you just aborted execution. Snippet 3 → Misleading familiarity return exits only the callback, not the loop forEach keeps iterating Output: 1, 3, 4 💡 Takeaway Control flow is not about syntax - it's about execution boundaries. Ask yourself: “What exactly am I returning from?” Function? Loop? Callback? Component? Because JavaScript won’t warn you. It will just… behave correctly in a way you didn’t expect. 🧩 Rule of thumb return in functions → exits function return in forEach → skips current iteration return in loops (top-level) → exits enclosing function (not just loop) The code looks similar. The runtime behavior is not. And that difference is where real-world bugs live. #javascript #reactjs #webdevelopment #softwareengineering #frontend #cleanCode
To view or add a comment, sign in
-
-
React.memo doesn't prevent re-renders. It just changes why they happen. ⚠️ You think it's optimized. The Profiler says otherwise. 𝗧𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗺𝗺𝗼𝗻 𝗺𝗶𝘀𝘁𝗮𝗸𝗲: function Parent() { const config = { theme: 'dark' }; // new object → new reference const handleClick = () => console.log('clicked'); // new function → new reference return <Child config={config} onClick={handleClick} />; } const Child = React.memo(({ config, onClick }) => { return <button onClick={onClick}>{config.theme}</button>; }); React.memo does a shallow comparison. config and handleClick are new references on every render — so Child re-renders every time. The memo did nothing. 𝗧𝗵𝗲 𝗳𝗶𝘅 — 𝘀𝘁𝗮𝗯𝗶𝗹𝗶𝘀𝗲 𝘁𝗵𝗲 𝗿𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀: function Parent() { const config = useMemo(() => ({ theme: 'dark' }), []); const handleClick = useCallback(() => console.log('clicked'), []); return <Child config={config} onClick={handleClick} />; } Stable UI requires stable references. 𝗪𝗵𝗲𝗻 𝗥𝗲𝗮𝗰𝘁.𝗺𝗲𝗺𝗼 𝗶𝘀 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝘄𝗼𝗿𝘁𝗵 𝗶𝘁: 1️⃣ 𝗣𝗿𝗼𝗽𝘀 𝗮𝗿𝗲 𝗽𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲𝘀 𝗼𝗿 𝘀𝘁𝗮𝗯𝗶𝗹𝗶𝘀𝗲𝗱 𝗿𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 Objects and functions without memoization = wasted effort. Strings, numbers, booleans compare correctly by default. 2️⃣ 𝗧𝗵𝗲 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁 𝗶𝘀 𝗴𝗲𝗻𝘂𝗶𝗻𝗲𝗹𝘆 𝗲𝘅𝗽𝗲𝗻𝘀𝗶𝘃𝗲 𝘁𝗼 𝗿𝗲𝗻𝗱𝗲𝗿 If the render is cheap, the comparison is the bottleneck. 3️⃣ 𝗬𝗼𝘂 𝗺𝗲𝗮𝘀𝘂𝗿𝗲𝗱 𝗶𝘁 𝗳𝗶𝗿𝘀𝘁 If you didn't measure it, you didn't optimize it. Open the Profiler. Find the actual bottleneck before reaching for the API. ⚠️ React.memo without stable references is optimisation theatre. It looks like performance work. It isn't. 🎯 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Memoisation is a tool, not a default. Reach for the Profiler before you reach for the API. 💬 Where did React.memo fool you into thinking something was optimized? Drop it below. 👇 #ReactJS #SoftwareEngineering #WebDev #FrontendEngineering #JavaScript
To view or add a comment, sign in
-
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐛𝐚𝐭𝐭𝐥𝐢𝐧𝐠 𝐩𝐡𝐚𝐧𝐭𝐨𝐦 𝐛𝐮𝐠𝐬 𝐢𝐧 𝐲𝐨𝐮𝐫 𝐑𝐞𝐚𝐜𝐭 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬? 𝐘𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐥𝐲𝐢𝐧𝐠 𝐭𝐨 𝐲𝐨𝐮. Often, we forget that `useEffect` captures variables from its surrounding scope. If those variables change but aren't in the dependency array, your effect might run with stale values from a previous render. This leads to subtle, hard-to-trace bugs where your logic seems correct but the data is wrong. Example: ```javascript function MyComponent({ userId }) { const [data, setData] = useState(null); // Problematic: Forgetting 'userId' in dependencies useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); // userId is referenced, but not in dependency array }, []); // <-- STALE CLOSURE if userId changes! // Correct: userId is a dependency useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); }, [userId]); // <-- Correctly re-runs when userId changes } ``` The linter usually warns you about this, but it's easy to dismiss or override. Understanding why it warns you about missing dependencies is crucial for stable and performant React applications. It’s not just about avoiding infinite loops; it's about guaranteeing your effects always operate with the latest state and props. What's your most common `useEffect` pitfall, or a bug that took you ages to trace back to a stale closure? #React #Frontend #TypeScript #JavaScript #WebDevelopment
To view or add a comment, sign in
-
🚀 Day 5/30 – State in React One of the most important concepts 🔥 Today I learned: ✅ State stores dynamic data inside a component → It allows components to manage and update their own data ✅ When state changes → React re-renders the UI → React automatically updates only the changed parts (efficient rendering ⚡) ✅ Managed using useState hook → The most commonly used hook in functional components ✅ State updates are asynchronous → React batches updates for better performance 💻 Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prev => prev + 1); // safe update }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); } 🔥 Key Takeaway: State is what makes React components interactive, dynamic, and responsive to user actions. #React #State #FrontendDevelopment #JavaScript #WebDev #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
I wrote the same component 3 times before I realised I only needed to write it once. Days 43–45/100 — 3 days deep into React, and the foundations are finally locking in. Here's everything that clicked this week: 🔹 Fragments — the invisible wrapper React needs a single parent element. But wrapping everything in a <div> pollutes your DOM. <> </> groups your JSX with zero DOM footprint. Clean markup. No ghost divs. No unexpected CSS side effects. 🔹 Map method — lists without the pain In vanilla JS, rendering a list meant loops + manual DOM updates. In React — one .map() call and every item in your array becomes a component. Dynamic. Clean. Automatic. 🔹 Conditional Rendering — 3 tools, 1 goal Making React show the right thing at the right time: • if-else — for complex logic outside JSX • Ternary — clean inline decisions inside JSX • Logical && — show something only when a condition is true Your UI should respond to data — not just display it. 🔹 Passing data via Props Props are how components talk to each other. Parent has data → passes it down → child receives and uses it. Without props, every component is an island. With props, they become a system. 🔹 Destructuring Props Instead of props.name, props.age, props.email everywhere — const { name, age, email } = props. Cleaner. Less repetitive. Readable at a glance. The biggest realisation from these 3 days? A component isn't a fixed UI block. It's a template. Props are the variables. Conditions are the logic. Map is the engine. That's the foundation of almost every React app in production. Day 45 done. 55 to go. 🚀 #100DaysOfCode #ReactJS #MERNStack #WebDevelopment #LearningInPublic #JavaScript #BuildInPublic
To view or add a comment, sign in
-
A well-structured frontend project makes development faster, scalable, and easier to maintain. Here is a clean Frontend Folder Structure I like to follow in modern React applications: 📁 api – Handles backend API connections 📁 assets – Static files like images, fonts, icons 📁 components – Reusable UI components 📁 context – Global state management using Context API 📁 data – Static data or mock content 📁 hooks – Custom React hooks for reusable logic 📁 pages – Application pages or routes 📁 redux – Advanced state management 📁 services – Business logic and API services 📁 utils – Helper and utility functions A proper folder structure keeps projects organized, scalable, and developer-friendly. How do you structure your frontend projects? 👨💻 #frontend #reactjs #redux #hooks #webdevelopment #javascript #coding #softwaredevelopmen
To view or add a comment, sign in
-
-
Your code is messy not because you're bad… It’s because you're mixing UI, Logic, and Data in one place. This is where Separation of Concerns (SoC) changes everything Imagine this: You click a button → API call happens → validation runs → UI updates Now ask yourself… Is all of that happening inside ONE component? If yes, that’s the problem. Here’s the better way: - UI (Presentation) Only handles what users see (No business logic, no API calls) - Logic (Brain) Handles validation, decisions, workflows - Data (Source) Handles API calls, DB, state Clean flow looks like this: UI → Logic → Data → Logic → UI Real shift (especially in React / Next.js): -Before: Everything inside one component -After: UI → Components Logic → Custom Hooks / Services Data → API layer If your components are getting “fat”… It’s a signal — you’re breaking SoC. Start small. Refactor one component today. You’ll feel the difference immediately. visit my website: https://lnkd.in/dFB_bqGu #webdevelopment #reactjs #nextjs #frontend #softwareengineering #coding
To view or add a comment, sign in
-
-
Stop scattering `localStorage` calls all over your React components. 🛑 If you are building an application that needs to save user input on the fly—like a daily expense tracker or a user settings paneldirectly writing to `localStorage` inside your components usually leads to messy `useEffect` blocks and out-of-sync UI states.🤧 The cleanest way to handle this is by abstracting it into a custom `useLocalStorage` hook. Here is why this pattern is a game-changer for frontend architecture: 1. Lazy Initialization: By passing a function to your initial `useState`, you only read from `localStorage` once during the initial render, saving valuable processing time. 2. Synchronized State: Your custom hook wraps the state setter function. Whenever you update the state in your app, the hook automatically pushes that exact same value to `localStorage`. You never have to worry about the UI and the storage getting out of sync. 3. Clean JSX: Inside your actual component, you just call `const [data, setData] = useLocalStorage('key', initialValue)`. It behaves exactly like a normal `useState`, keeping your JSX clean and focused on the UI, not the storage logic. Building reusable hooks doesn't just clean up your current codebase; it gives you a toolkit you can carry into every future projects. #ReactJS #WebDevelopment #FrontendTips #JavaScript #CleanCode #100DaysOfCode #Programming #LinkedInPolls #JavaScript #CareerGrowth #Coding #Developer #Coder #ComputerScience #SoftwareEngeering
To view or add a comment, sign in
Explore related topics
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