Here is a real-world debugging question asked during a JavaScript/React discussion. import { useEffect, useState } from "react"; export default function App() { const [data, setData] = useState(null); useEffect(() => { fetch("https://lnkd.in/gGnJ7utj") .then((res) => res.json()) .then((result) => { setData(result); console.log("Data:", data); }); }, []); return ( <div> <h1>{data?.title}</h1> </div> ); } ❓ Question: Why does console.log("Data:", data) print null even after calling setData(result)? Think about how React state updates work and when re-renders happen. 💡 Bonus: How would you correctly log the updated data? Drop your answers in the comments 👇 #Debugging #ReactJS #JavaScript #FrontendDevelopment #CodingInterview #ReactHooks #WebDevelopment #Developers
React State Update Issue with fetch Data
More Relevant Posts
-
JavaScript Closures are confusing… until they’re not ⚡ Most developers memorize the definition but struggle to actually understand it. Let’s simplify it 👇 💡 What is a closure? A closure is when a function 👉 remembers variables from its outer scope even after that scope is finished 🧠 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 fn(); // 3 ⚡ Why this works: inner() still has access to count even after outer() has executed 🔥 Where closures are used: • Data hiding • State management • Event handlers • Custom hooks in React #JavaScript #FrontendDeveloper #ReactJS #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Many developers confuse slice() and splice() in JavaScript. The difference is simple but important. 1️⃣ slice() — Creates a copy slice() returns a portion of an array without changing the original array. Example: const numbers = [10, 20, 30, 40, 50] const result = numbers.slice(1, 4) Result → [20, 30, 40] Original → [10, 20, 30, 40, 50] Use it when you want to extract data safely without modifying the source array. 2️⃣ splice() - Modifies the array splice() changes the original array. It can remove, add, or replace elements. Example 1 - Remove items: const numbers = [10, 20, 30, 40, 50] numbers.splice(2, 2) Result → [10, 20, 50] It removed 30 and 40 from the original array. Example 2 - Add Items : constnumbers= [10, 20, 50]; numbers.splice(2, 0, 30, 40); console.log(numbers); // [10, 20, 30, 40, 50] Explanation: It Start at index 2, Remove 0 items and Insert 30 and 40 Key Difference slice() → non-destructive (does not modify the array) splice() → destructive (modifies the array) Quick rule to remember slice → copy splice → change Understanding this small difference prevents many bugs, especially when working with React state and immutable data patterns. #javascript #webdevelopment #frontend #reactjs #programming
To view or add a comment, sign in
-
If you’re writing 5 files just to toggle a boolean... 🛑 You’re not scaling. You’re over-engineering. For a long time, I used Redux for almost everything in React. And honestly? It felt powerful... but also unnecessarily complex for 90% of my use cases. Recently, I switched to Zustand — and the difference is 🔥 Why Zustand just makes sense: ✅ Zero Boilerplate No Providers. No massive folder structures. Just create and use. ✅ Hook-Based If you know useState, you already understand Zustand. It feels like native React. ✅ Performance First It handles selective re-renders out of the box. Only the components that need the data will update. 💻 The "Store" is this simple: JavaScript import { create } from 'zustand' const useStore = create((set) => ({ count: 0, inc: () => set((state) => ({ count: state.count + 1 })), })) Use it anywhere: JavaScript function Counter() { const { count, inc } = useStore() return <button onClick={inc}>{count}</button> } ⚡ 𝗣𝗥𝗢 𝗠𝗢𝗩𝗘 (Most developers miss this): Use selectors to grab only what you need: const count = useStore((state) => state.count) This keeps your app lightning-fast even as your state grows massive. 📈 Since switching, my code is: → Simpler → Cleaner → Easier to maintain 🟣 Team Redux (The tried and true) 🐻 Team Zustand (The minimalist) #ReactJS #Zustand #JavaScript #WebDevelopment #Frontend #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
𝐈𝐬 𝐲𝐨𝐮𝐫 `𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭` 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐰𝐡𝐞𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝𝐧'𝐭? 𝐓𝐡𝐞 𝐜𝐮𝐥𝐩𝐫𝐢𝐭 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐦𝐨𝐫𝐞 𝐬𝐮𝐛𝐭𝐥𝐞 𝐭𝐡𝐚𝐧 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤. I just spent a frustrating hour debugging a seemingly random data refetch in a React component, only to trace it back to a non-primitive dependency in my `useEffect` array. When you pass an object or a function created inside your component directly into `useEffect`'s dependency array, React performs a reference equality check. Even if the contents of your object or the logic of your function haven't changed, its reference is new on every render. This forces your effect to re-run unnecessarily. Here's the common trap: ```javascript // 🚨 Problematic: 'config' object reference changes on every render const MyComponent = ({ id }) => { const config = { userId: id, status: 'active' }; useEffect(() => { fetchData(config); }, [config]); // 💥 Effect re-runs even if 'id' hasn't changed // ... }; ``` A cleaner, more performant way is to stabilize those references. For configuration objects, `useMemo` is your friend: ```javascript // ✅ Solution: 'memoizedConfig' reference is stable as long as 'id' is const MyComponent = ({ id }) => { const memoizedConfig = useMemo(() => ({ userId: id, status: 'active' }), [id]); useEffect(() => { fetchData(memoizedConfig); }, [memoizedConfig]); // ... }; ``` This prevents wasted renders and unnecessary side effects, keeping your app snappier and less buggy. It's often the small details in `useEffect` that lead to the biggest headaches! Have you ever battled a similar `useEffect` dependency bug? What was your fix? #ReactJS #FrontendDevelopment #JavaScript #WebDev #ReactHooks
To view or add a comment, sign in
-
🚫 Can We Cancel a Promise in JavaScript? 🎯 Imagine this: An API call is triggered… The user clicks “Cancel” or navigates away… 👉 But the request is still running in the background. Why? Because Promises in JavaScript cannot be cancelled once they start. ⚠️ The Reality A Promise is like a train 🚆 Once it leaves the station, it cannot be stopped midway. ✅ So What Can We Do? Even though we can’t cancel the Promise itself, we can control its behavior 👇 🔹 1. AbortController (Modern Approach) Cancel network requests like fetch: const controller = new AbortController(); fetch('/api/data', { signal: controller.signal }); controller.abort(); // stops the request 🔹 2. Manual Flags (Control Execution) let isCancelled = false; setTimeout(() => { if (!isCancelled) { console.log("Executed"); } }, 2000); isCancelled = true; 🔹 3. (Angular Devs 👀) Use RxJS switchMap() 👉 Automatically cancels previous API calls and keeps only the latest 💡 Key Insight ❌ You can’t cancel a Promise ✅ But you CAN cancel its effect 🚀 Why This Matters This pattern is critical for: API calls Search inputs Rapid user interactions Preventing stale data issues 💬 Let’s Discuss How do you handle cancellation in your apps? 👉 AbortController, RxJS, or custom logic? #JavaScript #Angular #RxJS #AsyncProgramming #Promises #AbortController #FrontendDevelopment #CodingTips #WebDevelopment #TechInterviews
To view or add a comment, sign in
-
-
Most developers reach for an array by default. But sometimes, that's the wrong tool. When you use array.find() to look up a value, it scans from the start every single time. That's O(n) time complexity. With 10 items, unnoticeable. With 10,000 items, your server feels it. A Map object solves this. Instead of this: const user = users.find(u => u.id === id) Do this: const userMap = new Map(users.map(u => [u.id, u])) const user = userMap.get(id) Map lookups are O(1). It doesn't matter if you have 10 items or 10 million, the lookup time stays the same. This only makes sense when you have a fixed dataset and are doing repeated lookups. If you're looking up once, array.find() is perfectly fine. But if you're hitting that array multiple times, consider reaching for a Map instead. #JavaScript #NodeJS #SoftwareEngineering #WebDevelopment #Performance
To view or add a comment, sign in
-
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
Development lies. Everything works. Perfect data. No errors. Then production hits. 💥 user.name → crash ❌ Because… data isn’t always perfect. Now I write: user?.name ?? "N/A" ✅ This is called optional chaining + Nullish coalescing 💡 Lesson: Don’t trust API data. Handle it. Have you faced this in production? 👇 #ReactJS #JavaScript #Frontend #Web
To view or add a comment, sign in
-
-
⚠️ Props vs State in React If you don’t understand this properly… 👉 React will ALWAYS feel confusing. Let’s simplify it 👇 --- 🧩 Props (Think: Parameters) ✔ Passed from Parent → Child ✔ Read-only (cannot be changed) ✔ Used to send data Example: ```jsx <Child name="Kiran" /> ``` --- ⚙️ State (Think: Internal Memory) ✔ Managed inside the component ✔ Can be updated ✔ Controls UI behavior Example: ```jsx const [count, setCount] = useState(0); ``` --- 🔥 The Biggest Mistake: Trying to change props ❌ 👉 You can’t. --- 💡 Key Insight: Props = Input State = Internal Data --- 📌 Simple Analogy: Props = Function arguments 📥 State = Local variables 📦 --- 🧠 Pro Tip: If data needs to change → use State If data is passed → use Props --- 💬 Question: What confused you more when learning React? Props or State? #ReactJS #Frontend #JavaScript #WebDevelopment #Coding #LearnReact
To view or add a comment, sign in
-
-
Using index as a key is dangerous Every React developer has written this at least once. items.map((item, index) => ( <li key={index}>{item}</li> )) Looks fine. Works fine. But it isn't This is Post 5 of the series: 𝗥𝗲𝗮𝗰𝘁 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱 Where I explain what React is actually doing behind the scenes. Here's what actually happens when you use index as key: You delete one item from a list. React doesn't know which item was removed. It just looks at positions. So it re-renders everything from that index downward. Input states get mismatched. Animations break. Bugs appear that you can't even reproduce consistently. And... No error. Just... wrong behavior. 🔑 Here's what React actually needs: A key isn't just something unique. It needs to be stable, unique, AND tied to the data — not the position. ❌ key={index} → breaks on delete, sort, filter ❌ key={Math.random()} → new key every render = React destroys and recreates the node ✅ key={item.id} → stable, reliable, React knows exactly who is who The rule is simple: If your list can ever be reordered, filtered, or deleted from... index as key will silently break your UI. Use your data's ID. If it doesn't have one, generate it at creation — not during render. const newItem = { id: crypto.randomUUID(), name: "New Task" } One tiny prop. Massive impact on how React tracks your entire list. In Post 6 of React Under the Hood: What Happens When You Call setState Follow Farhaan Shaikh if you want to understand react more deeply. 👉 Read the previous post - Understanding diffing algorithm: https://lnkd.in/dzW3NP_V #SoftwareEngineering #ReactJS #WebDevelopment #JavaScript #FrontendDevelopment #BuildInPublic #LearnInPublic #ReactUnderTheHood
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