A Common React Mistake We Make as React/JS Developers. I have found that one small mistake in React can create very weird UI bugs while working on using Index as Key in a List. Let me explain with an example. Check this code for displaying a list - {items.map((item, index) => ( <div key={index}>{item.name}</div> ))} The above piece of code is something we commonly use. It looks fine, but sometimes it can be dangerous - and we often ignore it. Let me explain why. At first, everything looks fine. No errors. But the real problem starts when the list changes - during insertion or deletion. Imagine the list is: 0 - React 1 - Node 2 - Next Now suppose we delete "React" (index 0). Hence, the new list becomes: 0 - Node 1 - Next But here is the problem. React thinks: Item with key 0 still exists. Item with key 1 still exists. Because the keys (0 and 1) are still there. So instead of understanding: "React was removed" React thinks: "React became Node" "Node became Next" It reuses the old components and just changes the data. Result: Wrong component updates. How can we fix it? Using a stable id as the key. {items.map((item) => ( <div key={item.id}>{item.name}</div> ))} Now imagine: id: 101 - React id: 102 - Node id: 103 - Next We delete React (101). React sees: 101 is gone 102 still exists 103 still exists So, it removes that exact component. Share your thoughts in the comment box. hashtag #ReactJS hashtag #JavaScript hashtag #WebDevelopment hashtag #FrontendDevelopment hashtag #ReactDeveloper hashtag #CodingMistakes hashtag #SoftwareDevelopment hashtag #LearnToCode hashtag #Programming
React Key Mistake: Using Index as Key
More Relevant Posts
-
⚠️ A Common React Mistake We Make as React/JS Developers. I have found that one small mistake in React can create very weird UI bugs while working on using Index as Key in a List. Let me explain with an example. Check this code for displaying a list - {items.map((item, index) => ( <div key={index}>{item.name}</div> ))} The above piece of code is something we commonly use. It looks fine, but sometimes it can be dangerous - and we often ignore it. Let me explain why. At first, everything looks fine. No errors. But the real problem starts when the list changes - during insertion or deletion. Imagine the list is: 0 - React 1 - Node 2 - Next Now suppose we delete "React" (index 0). Hence, the new list becomes: 0 - Node 1 - Next But here is the problem. React thinks: Item with key 0 still exists. Item with key 1 still exists. Because the keys (0 and 1) are still there. So instead of understanding: "React was removed" React thinks: "React became Node" "Node became Next" It reuses the old components and just changes the data. Result: Wrong component updates. How can we fix it? Using a stable id as the key. {items.map((item) => ( <div key={item.id}>{item.name}</div> ))} Now imagine: id: 101 - React id: 102 - Node id: 103 - Next We delete React (101). React sees: 101 is gone 102 still exists 103 still exists So, it removes that exact component. Share your thoughts in the comment box. #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #ReactDeveloper #CodingMistakes #SoftwareDevelopment #LearnToCode #Programming
To view or add a comment, sign in
-
-
📌 JavaScript works… until it doesn’t. That’s the moment I truly understood the value of TypeScript in React. If you’re building React apps and want fewer bugs, better readability, and safer refactoring, here’s how TypeScript fits into everyday React development 👇 1.Functional Components type Props = { title: string; isActive?: boolean; }; const Header: React.FC<Props> = ({ title, isActive = false }) => { return <h1>{isActive ? title : "Inactive"}</h1>; }; 2.Props with Strong Typing type ButtonProps = { label: string; onClick: () => void; }; const Button = ({ label, onClick }: ButtonProps) => ( <button onClick={onClick}>{label}</button> ); 3.State with Type Safety const [count, setCount] = useState<number>(0); const [user, setUser] = useState<{ name: string; age: number } | null>(null); 4. Event Handlers const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { console.log(e.target.value); }; For more Understanding watch following videos: -FreeCode Camp : https://lnkd.in/dhBQnVsD -PedroTech : https://lnkd.in/dbnKP-vD #React #TypeScript #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #LearningInPublic
To view or add a comment, sign in
-
💡 Small React/Next.js Tip I Learned Today While working on a Next.js project, I needed to create a reusable configCreator utility. Example: const configCreator = () => ({ id: "id", label: "Option 1", icon: <Info size={12} /> }); Since I wanted to store it inside a utility file and reuse it across multiple places, I ran into an interesting problem. Because I was using a JSX component (<Info />) inside the util file, I had to change the file extension from .ts → .tsx. The issue was that this file already contained many other utility functions, so just to add one function using JSX, the whole file needed to become .tsx. The Better Approach I Found Instead of JSX, I used React.createElement. const configCreator = () => ({ id: "id", label: "Option 1", icon: React.createElement(Info, { size: 12 }) }); This allowed me to keep the file as .ts, since React.createElement doesn't require JSX. Why This Is Useful ✔ Keeps utility files clean and framework-agnostic ✔ Avoids unnecessary .tsx conversions ✔ Makes configs easier to reuse across the codebase Curious to hear from other React developers 👇 How would you tackle this in your React codebase? Keep it .tsx? Use React.createElement? Or structure the config differently? #React #NextJS #FrontendDevelopment #JavaScript #WebDevelopment
To view or add a comment, sign in
-
Closures in React: powerful concept, subtle bugs Closures are a fundamental concept in JavaScript. They also explain some of the most confusing bugs that appear in React applications. A closure happens when a function captures variables from the scope where it was created. Those variables remain accessible even after the outer function has finished executing. In React, every render creates a new scope. When a function is defined inside a component, it closes over the values from that specific render. This becomes important when using hooks like useMemo and useCallback. If the dependency array is incomplete, the function may keep referencing outdated values from a previous render. Common situations where this appears: • useCallback capturing an old state value • useMemo computing something with stale props • event handlers referencing outdated variables The result is what developers often call a stale closure. The UI updates, but the function is still working with old data. This is why dependency arrays matter. They are not only about performance. They ensure the function is recreated when its captured values change. A good rule of thumb is simple. If a value is used inside useMemo or useCallback, it usually belongs in the dependency array. I added a small example in the comments showing how a stale closure happens in practice and how to fix it.
To view or add a comment, sign in
-
-
How I Understood ActivityHook in React(Activity Hook) One day I built a simple toggle in React: 👉 Switch between Home and User Form At first, I wrote it the usual way: </>Jsx {showHome ? <Home /> : <UserForm />} And it worked. But there was a problem. Every time I switched: • Form inputs got cleared 😩 • State was lost • Everything reset 🧠 Before (without Activity) React thinks like this: 👉 “Remove one component, mount the other.” So switching means: • Destroy → Create again • State = gone 💡 Then I discovered Activity </>Jsx import { useState, Activity } from "react"; export default function App() { const [showHome, setShowHome] = useState(true); return ( <> <button onClick={() => setShowHome(true)}>Home</button> <button onClick={() => setShowHome(false)}>User Form</button> <Activity mode={showHome ? "visible" : "hidden"}> <Home /> </Activity> <Activity mode={!showHome ? "visible" : "hidden"}> <UserForm /> </Activity> </> ); } 🧠 After (with Activity) React now thinks like this: 👉 “Keep both components alive… just hide one.” So switching means: • No unmount • No reset • State stays intact ✅ 🔥 Real-life example It’s like switching tabs on your phone: • App doesn’t close • It just goes to background 💡 The lesson I learned Before: 👉 Render vs Unmount After: 👉 Visible vs Hidden That small shift changed everything. Now I don’t ask: 👉 “Should I render this?” I ask: 👉 “Should I keep it alive?” Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useEffect #useMemo #useCallback #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #React19 #ActivityHook
To view or add a comment, sign in
-
-
How I Understood React State Updates One day I wrote this small React code: import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); setCount(count + 1); setCount(count + 1); console.log(count); }; console.log(count); return ( <div> <h1>{count}</h1> <button onClick={handleClick}>Increment</button> </div> ); } And I thought something very simple would happen. I clicked the button and expected: 0 → 3 Because I increased the count three times. But React surprised me. The value became: 0 → 1 And I asked myself: 👉 Why didn't it increase to 3? So I stopped thinking like a JavaScript developer… and started thinking like React. What React actually sees React batches state updates. All three lines read the same old value. setCount(count + 1); setCount(count + 1); setCount(count + 1); • For React, this becomes: setCount(1) setCount(1) setCount(1) • So the final result is simply: 1 Not 3. • The correct way When the new state depends on the previous state, React gives us a better pattern: setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React updates step by step. Result: 0 → 3 The lesson I learned State updates in React are not immediate. React schedules them and processes them together. So whenever state depends on the previous value, I now ask myself: 👉 Should I use the functional update? Small detail. Big difference. Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useState #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook
To view or add a comment, sign in
-
-
React developers: stop mutating state. Use the spread operator instead. Wrong (mutates): user.role = 'admin' setUser(user) // React won't re-render! Right (creates new object): setUser({ ...user, role: 'admin' }) More React patterns: Add to array: setItems([...items, newItem]) Remove from array: setItems(items.filter(item => item.id !== removeId)) Update array item: setItems(items.map(item => item.id === targetId ? { ...item, completed: true } : item )) Merge state: setForm({ ...form, ...updates }) Nested state update: setUser({ ...user, settings: { ...user.settings, theme: 'dark' } }) Why spread over mutation: → React detects changes properly → Prevents stale closure bugs → Enables time-travel debugging → Makes state updates predictable → Follows immutability principles In React, immutability isn't optional. The spread operator makes it easy. #React #JavaScript #WebDevelopment #FrontendDev #ReactJS
To view or add a comment, sign in
-
C# on the Frontend: Is the React Era Fading for .NET Devs? 🧐 For years, the rule was simple: Back-end in .NET, Front-end in React/Angular. But in 2026, with the massive improvements in Blazor (and .NET 10), that line is blurring faster than ever. As a Back-end developer, I’ve been experimenting with both, and here is what I’ve noticed: 🚀 Why Blazor is winning for Enterprise: Shared Logic: Using the same DTOs and Validation logic on both sides is a productivity cheat code. Type Safety: Say goodbye to the "JavaScript Guessing Game." End-to-end type safety with C# is a lifesaver. The Ecosystem: If you are already in the .NET ecosystem, the learning curve is almost flat. ⚛️ Why React still holds the crown: The Ecosystem: The sheer number of libraries and community support is still unmatched. Hydration & Speed: For consumer-facing apps, React’s lightweight footprint is still hard to beat. The Verdict? If I'm building a complex internal tool or a high-performance Enterprise dashboard here in the Smart Village, I’m picking Blazor every single time. For public-facing, SEO-heavy sites, React stays in my pocket. I want to hear from the Full Stack community: Are you still jumping between C# and TypeScript, or have you consolidated your entire stack into .NET? Is Blazor ready to take over the throne? 👑 #dotNET #Blazor #ReactJS #WebDevelopment #FullStack #SoftwareArchitecture #Programming #CodingLife
To view or add a comment, sign in
-
-
👨💻 As a Java Developer, I was comfortable building logic-heavy applications, but when it came to creating dynamic and interactive user interfaces, things started getting complicated. 🚨 The Problem: Using traditional JavaScript, even small UI updates required reloading large parts of the page. Managing the DOM manually became messy, time-consuming, and hard to scale. 💡 That’s where React comes into the picture. React introduced a completely new way of thinking — breaking the UI into reusable components and updating only what’s necessary using the Virtual DOM. ⚡ The Result: ✔ Faster and smoother UI updates ✔ Clean and maintainable code ✔ Reusable components ✔ Better user experience 🚀 Now I understand why modern applications rely so heavily on React. 🚀 No wonder modern apps like Facebook, Instagram, and Netflix rely on React! #ReactJS #WebDevelopment #Frontend
To view or add a comment, sign in
-
-
This video provides a comprehensive introduction to React, the powerful JavaScript library used to build dynamic and interactive user interfaces. Whether you are a beginner starting your web development journey or a developer looking to understand the shift from class-based to functional components, this guide covers everything you need to build efficient and maintainable applications. What You Will Learn: Core Concepts: Understand why React is component-driven and how it facilitates the creation of Single-Page Applications (SPAs) that feel "lightning-fast" because they don't require full page reloads. The Virtual DOM: Learn the "magic" behind React’s performance. We explain how React uses a lightweight sketch of your UI to compute differences and update only what's necessary in the real Browser DOM. JSX (JavaScript XML): Discover how to write HTML-like code directly within your JavaScript to define the structure of your UI. Functional vs. Class Components: Explore the foundational differences between the two. While Class Components were the traditional way to manage state, Functional Components are now the recommended standard thanks to the introduction of React Hooks. State & Props: Learn how to manage a component's "memory" with state and how to pass data dynamically between components using props. React Hooks: A deep dive into essential hooks like useState for data management and useEffect for handling side effects like data fetching and subscriptions. Conditional Rendering & Lists: Master techniques for showing/hiding elements and using the .map() method to render collections of data efficiently with unique keys. Environment Setup: Get up and running quickly by installing Node.js and using modern build tools like Vite for a faster development experience. Advanced Insights: We also touch on React Architecture, including best practices for directory structures, separate logic and design, and when to "lift state up" to share data between sibling components. Timestamps: 0:00 - Introduction to React & SPAs 2:15 - Virtual DOM Explained 5:00 - JSX Basics 8:30 - Functional vs. Class Components 12:45 - Props and State Management 18:20 - Mastering Hooks: useState & useEffect 25:10 - Rendering Lists and Keys 30:45 - Setup & Best Practices Links & Resources: Official React Quick Start Guide React Developer Roadmap Modern build tools: Vite
Demystifying React
https://www.youtube.com/
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