Ever had that moment where your code should work, but console.log insists your import is undefined? 🤔 We hit a fascinating bug today while integrating a mini-app into our super-app. One specific Redux thunk (getPdfData) was undefined, while every other thunk worked perfectly. 🛠️ The Problem: It turned out to be a classic circular dependency. 1️⃣ The Store starts to load... 2️⃣ It needs our PDF Slice... 3️⃣ The PDF Slice needs the PDF Thunk... 4️⃣ The PDF Thunk needs the API Utility... 5️⃣ ...and the API Utility needed the Store to get tokens! 🔄 The module system couldn't resolve this loop, so it returned undefined for the weakest link in the chain. 📉 The Solution: We broke the loop using Dependency Injection. Instead of the API utility importing the store (creating the loop), we refactored it so the store is injected into the API layer after it's fully created. ✅ Key Takeaway: Low-level utilities (like API clients) should never import high-level modules (like the Redux store). It’s a sure path to circular dependencies. Injecting dependencies instead of importing them keeps your modules clean and your load order predictable. 💡 It's a great reminder that sometimes the most frustrating bugs have the cleanest architectural solutions! ✨ #ReactNative #Redux #TypeScript #JavaScript #SoftwareArchitecture #BugBash
How to avoid circular dependencies in Redux with Dependency Injection
More Relevant Posts
-
Async Redux confused me more than the code itself. Every diagram showed a simple loop. None explained where the API actually happens. This one finally made it click. 📌 The real async Redux flow in 7 steps: 1️⃣ View: User triggers an action (FETCH_USER_REQUEST) 2️⃣ Middleware: Thunk/Saga intercepts it 3️⃣ API Call: Side effect happens here 4️⃣ Action #2: Middleware dispatches FETCH_USER_SUCCESS with payload 5️⃣ Reducer: Pure function. Updates state only on success action 6️⃣ State: Central store gets fresh data 7️⃣ View Update: React re-renders UI 🔁 That’s the loop: View → Action → Middleware → API → Action → Reducer → State → View This diagram is one of the clearest visual explanations of async data flow in Redux that I’ve seen. If you’re learning Redux, save this. 👇 I’m curious: Which async approach do you use in React today? Saga? Thunk? RTK Query? Something else? #Reactjs #Redux #JavaScript #WebDevelopment #Frontend #StateManagement #ReduxToolkit #AsyncProgramming #ReactDevelopers #SoftwareEngineering #LearningInPublic #WebDevCommunity
To view or add a comment, sign in
-
-
Remember when every API started with a controller folder? Those days might be numbered. Hono's documentation has a bit of a silent killer in its best practices which make it clear: they don't belong in modern JavaScript apps. It's an interesting stance. Controllers used to feel like the gold standard for structuring HTTP logic. They brought order, separation, and a sense of architecture. But maybe that era's ending? In Conversation Piece's debut alongside the Hustle Hammer series, I dig into whether the controller pattern still earns its keep in 2025 - or if frameworks like Hono are showing us a better way to think about routing and request handling. Give it a read and tell me where you stand: are controllers still part of your toolkit, or are you moving on? https://lnkd.in/e8tNRsYw
To view or add a comment, sign in
-
Day 10, and I’ve moved on from simple lists (arrays) to managing complex data with JavaScript Objects! If arrays are just numbered lists, objects are like personalized file folders that let you organize information using descriptive names (keys) instead of numbers. This is how you structure anything with multiple properties like a user profile or a product all inside one clean variable. I learned the two main ways to grab information from them: Dot Notation (e.g., user.name) and Bracket Notation (e.g., user['email']). It feels like the final piece of the data organization puzzle! When you’re dealing with objects in JavaScript, when is it necessary or better to use Bracket Notation over Dot Notation?" #objects #javascript #31dayschallenge #growth #frontend #webdevelopment
To view or add a comment, sign in
-
-
Context API vs. Redux: Stop the Confusion. Here’s the 2-minute rule that can help. Choosing between React's built-in Context API and the popular Redux library is a common dilemma. The key is to think about scale and frequency. ⤷Use Context API for: -Simple, infrequent updates, like a dark mode toggle or a logged-in user's name. -Avoiding "prop drilling" on a small-to-medium scale. -When you prefer a lightweight, built-in React solution with less setup. ⤷Use Redux for: -Large, complex applications with state that changes frequently. -Centralizing a single "source of truth," like a shopping cart or dashboard data. -Debugging complex state issues with powerful DevTools, which Context lacks. -Predictable state updates with a structured flow of actions and reducers. ⤷Username & Notification Example: →You have two states: -Username: Rarely changes -Notifications: Changes frequently →With Context: If you put both in one context, every time notifications update, all components showing the username re-render too. This is inefficient. To fix it, you must split your contexts, adding complexity. →With Redux: Redux lets components subscribe only to the state they need. The component showing notifications subscribes to notifications. Lot of components showing the username do not re-render when a notification arrives. ⤷The takeaway: -Context is perfect for static or low-frequency global data. -Redux shines when your state is dynamic, shared, and heavily updated. ⤷Your take: -Have you ever migrated from Context to Redux? -What was your sign that it was "time for a cannon"? Share your experience in the comments! #React #JavaScript #WebDevelopment #Redux #ContextAPI #StateManagement
To view or add a comment, sign in
-
Day 12 of JS series - by Rohit Negi What I learned: ✅ forEach() – Iterates over every element in an array. ✅ filter() – Filters elements from an array based on a specific condition and returns a new array. ✅ map() – Transforms each element of an array and returns a new array. ✅ reduce() – Reduces an array to a single value (of any data type). ✅ Set – A data structure that stores unique values. ✅ Map – A data structure that stores key-value pairs, where both keys and values can be of any data type. #LearnInPublic #JavaScript #WebDevelopment
To view or add a comment, sign in
-
-
💭 𝐄𝐯𝐞𝐫 𝐰𝐨𝐧𝐝𝐞𝐫𝐞𝐝 𝐡𝐨𝐰 𝐬𝐭𝐨𝐜𝐤 𝐦𝐚𝐫𝐤𝐞𝐭 𝐝𝐚𝐬𝐡𝐛𝐨𝐚𝐫𝐝𝐬 𝐜𝐨𝐧𝐭𝐢𝐧𝐮𝐨𝐮𝐬𝐥𝐲 𝐮𝐩𝐝𝐚𝐭𝐞 𝐝𝐚𝐭𝐚 𝐞𝐯𝐞𝐫𝐲 𝐬𝐞𝐜𝐨𝐧𝐝 - 𝐰𝐢𝐭𝐡𝐨𝐮𝐭 𝐲𝐨𝐮 𝐫𝐞𝐟𝐫𝐞𝐬𝐡𝐢𝐧𝐠 𝐭𝐡𝐞 𝐩𝐚𝐠𝐞? 📈 That magic happens because of something called Polling. In simple terms, polling means automatically fetching data from the server at regular intervals, keeping your UI fresh and real-time. What this does: ➤ Automatically refetches data every 5 seconds ➤ Keeps your app synced with real-time updates ➤ No manual reloads needed! 💡 Bonus Tip: You can even stop polling when the browser tab is inactive by setting refetchIntervalInBackground: false - great for optimizing performance. So the next time you see live dashboards or dynamic analytics updating instantly, remember — it’s Polling making it happen! 🔥 #ReactJS #ReactQuery #FrontendDevelopment #WebDevelopment #JavaScript #ReactHooks #Coding #TechLearning
To view or add a comment, sign in
-
-
We’ve all been there debugging a perfectly fine API response... only to realize your data is failing validation because of a few invisible spaces. These trailing spaces can silently break string comparisons, UI bindings, and even backend validations. So, I wrote a simple recursive utility in JavaScript to clean them deeply. 🧹 𝗪𝗼𝗿𝗸𝘀 𝗳𝗼𝗿: Nested objects Arrays Deeply nested strings 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝗲𝗿𝘀 𝗹𝗼𝘃𝗲 𝗮𝘀𝗸𝗶𝗻𝗴 𝗮𝗯𝗼𝘂𝘁: Recursion Object traversal Data normalization or deep cloning This question can easily appear as: “Write a function to remove spaces from all string values in a nested object.” #JavaScript #WebDevelopment #CodingTips #Frontend
To view or add a comment, sign in
-
-
👨💻 Tired of scattered console.log() everywhere? Let’s talk about why you should create your own logger.js in React — and how it can instantly make your debugging cleaner, safer, and more professional. 🔍 Why use a Logger instead of console.log()? In real-world projects, you don’t just log messages — you manage them. A proper logger helps you: ✅ Organize logs by level (info, warn, error, debug) ✅ Hide logs automatically in production ✅ Send logs to your backend or monitoring tools (Sentry, LogRocket, etc.) ✅ Maintain a consistent format across the team // src/utils/logger.js const isProd = process.env.NODE_ENV === "production"; const logger = { info: (...args) => !isProd && console.info("[INFO]", ...args), warn: (...args) => !isProd && console.warn("[WARN]", ...args), error: (...args) => console.error("[ERROR]", ...args), // keep visible debug: (...args) => !isProd && console.debug("[DEBUG]", ...args), }; export default logger; Use it anywhere: import logger from "../utils/logger"; logger.info("App started"); logger.debug("User data fetched"); logger.error("Failed to load dashboard", error); 🎯 Benefits: No random logs in production Easier debugging in dev mode Professional code structure Easy to integrate with monitoring tools #ReactJS #JavaScript #WebDevelopment #CleanCode #FrontendTips #loggerjs #Developers #CodingBestPractices
To view or add a comment, sign in
-
Most developers use localStorage and sessionStorage without really knowing the difference. I was the same — until one bug forced me to actually read the docs. Here’s the difference 👇 🧠 localStorage - Data persists even after the browser is closed. - Great for saving user preferences, themes, or tokens that don’t expire. ⚙️ sessionStorage - Data clears once the tab or window is closed. - Perfect for temporary data like form states or one-session inputs. Both store data as key-value pairs in the browser — but persistence changes everything. I learned one rule from that bug: → “Use sessionStorage when you want memory. → Use localStorage when you want permanence.” Small detail. Big difference. #javascript #webdevelopment #frontend #softwareengineering #learnbybuilding #reactjs
To view or add a comment, sign in
-
-
💡 structuredClone() vs JSON.parse(JSON.stringify()) Both are used for deep copying objects in JavaScript, but they’re not the same. 🧠 structuredClone() Creates a true deep copy (recursively copies nested data). Supports complex types: Date, Map, Set, Blob, etc. Handles circular references safely. Faster and more reliable. const clone = structuredClone(obj); ⚠️ JSON.parse(JSON.stringify()) Works only for simple JSON-safe data. Loses functions, Dates, Maps, Sets, and Symbols. Crashes on circular references. ✅ Use structuredClone() whenever available (modern browsers & Node 17+). Use the JSON trick only for plain, simple data. #JavaScript #WebDevelopment #Frontend #DeepCopy #CodingTips
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