Ever found yourself chaining .filter().map() and thought, "There must be a cleaner way"? 🤔 If you're working with arrays in JavaScript, you probably use .map() every day. But what if you need to turn one item into multiple elements, or skip some items entirely without creating an ugly nested array? That’s where .flatMap() becomes your best friend. As a React dev, I used to struggle with rendering logic when one data point needed to produce two components (like a Label and a Divider). Check out the difference: const items = ['React', 'Next.js']; ❌ The old way (creates nested arrays) items.map(item => [item, 'Separator']); Result: [['React', 'Separator'], ['Next.js', 'Separator']] - React hates this! ✅ The flatMap way (flattens as it maps) items.flatMap(item => [item, 'Separator']); Result: ['React', 'Separator', 'Next.js', 'Separator'] - Clean & flat! Why I love using it in React: * Conditional Rendering: Instead of filtering first and then mapping, you can just return an empty array [] for items you want to skip. It's cleaner and more performant because you only iterate once. * Cleaner JSX: No more fragmented arrays or weird index % 2 logic to insert dividers between list items. * Performance: It combines two operations (map + flat) into a single pass. Next time you're about to chain .filter().map(), try reaching for .flatMap() instead. Your code (and your future self) will thank you. How often do you use flatMap in your projects? Let me know in the comments! 👇 #JavaScript #WebDevelopment #ReactJS #CodingTips #CleanCode #Frontend
Payam Sharifi’s Post
More Relevant Posts
-
The Virtual DOM is often explained as a "performance optimization." It isn't. Rich Harris made this argument in 2018 and it still stands — VDOM adds a layer of work on top of DOM operations, not below them. What it gives you is a programming model: describe the output, not the steps. I wrote a tutorial that builds the entire engine from scratch in 71 lines of vanilla JS. Four functions. Zero dependencies. Every design decision is explicit — no magic. If you've ever wondered what React's reconciler actually does, this is the fastest path to understanding it. https://lnkd.in/dXvCzgXy #javascript #react #webdev #frontend #tutorial
To view or add a comment, sign in
-
setTimeout(fn, 0) runs immediately. Promise callbacks and setTimeout callbacks go in the same queue. The event loop is part of V8. ============================================= I believed all three. Every single one is wrong. I wrote about the mental model I had to completely unlearn — with interactive visualizations you can step through yourself. If you've ever had a spinner that never spins, an async forEach that silently fails, or a sequential await killing your performance without you noticing — this is the article I wish I'd read sooner. https://lnkd.in/gBTvuX2k #javascript #eventloop #webdev #frontend #v8 #async
To view or add a comment, sign in
-
𝐀𝐫𝐞 𝐲𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐡𝐨𝐨𝐤𝐬 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐰𝐢𝐥𝐝? I just debugged a subtle React re-render loop that comes up more often than you'd think. Here's the trap: When you define an object or array directly inside your component's render function and then pass it as a dependency to `useEffect`. ```javascript function MyComponent() { const settings = { fetchLimit: 10, isActive: true }; useEffect(() => { // This effect will re-run on every render // because `settings` is a new object reference each time. fetchData(settings); }, [settings]); // 🚨 Problem here! // ... } ``` Even if the contents of `settings` are identical, its reference changes on every render. React sees a "new" dependency and re-runs your effect. Hello, infinite loops or wasted API calls! The fix? Stabilize your dependencies. Use `useMemo` if the object/array is derived from other stable props/state, or define it outside the component if it's truly constant. ```javascript function MyComponent() { const settings = useMemo(() => ({ fetchLimit: 10, isActive: true }), []); // ✅ Stabilized! useEffect(() => { fetchData(settings); }, [settings]); // Now `settings` reference is stable // ... } ``` This simple tweak can save a lot of head-scratching and dramatically improve performance. Always remember: `useEffect` compares dependencies by reference, not by value. What's your go-to strategy for taming `useEffect` dependency arrays? Share your tips! #React #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
"JS Fundamentals Series #4: Closures & First-Class Functions" Ever wondered how a function remembers variables even after its parent has finished executing? That's the magic of Closures - one of the most powerful concepts in JavaScript. 👉 Closures: A closure is formed when a function remembers the variables from its lexical environment, even after the outer function has returned. 👉 First-Class Functions: In JavaScript, functions are treated like any other value - they can be assigned to variables, passed as arguments, or returned from other functions 🔹Explanation - Closures combines a function with its surrounding scope. - They allow data privacy and state retention. - First-class functions make higher-order functions possible (functions that take or return another functions). 🔹 Example function outer() { let count = 0; return function inner() { count++; return count; } } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Here, inner() remembers count even after outer() has finished — that’s a closure in action. 🔹Why It Matters - Enables powerful patterns like currying, memoization, and event handling. - Helps write modular, reusable, and maintainable code. - Essential for understanding modern frameworks like React. 💡 Takeaway: Closures aren’t just theory — they’re the backbone of how JavaScript manages state and builds advanced patterns. #JavaScript #WebDevelopment #Frontend #ReactJS #CodingTips #DeveloperCommunity #NamasteJS #LearningJourney #TechExplained #CareerGrowth "Closures: Functions carry their lexical environment with them 👇"
To view or add a comment, sign in
-
-
𝐈𝐬 𝐲𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐢𝐧𝐟𝐢𝐧𝐢𝐭𝐞𝐥𝐲 𝐨𝐫 𝐦𝐨𝐫𝐞 𝐭𝐡𝐚𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝? 𝐓𝐡𝐞 𝐜𝐮𝐥𝐩𝐫𝐢𝐭 𝐢𝐬 𝐨𝐟𝐭𝐞𝐧 𝐬𝐢𝐦𝐩𝐥𝐞𝐫 𝐭𝐡𝐚𝐧 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤. One of the most common pitfalls with `useEffect` in React is including non-primitive values (objects, arrays, functions) directly in its dependency array without proper handling. Every time your component re-renders, if you create a new object or array literal, or a new function instance, its reference changes. ```javascript useEffect(() => { /* fetch data using config */ }, [config]); ``` If `config` is an object created directly inside your component, even if its properties are identical, `useEffect` sees a new object reference on every render. This forces the effect to re-run, leading to unnecessary computation, API calls, or even infinite loops. **The Fix:** 1. **Destructure Primitives:** If you only need specific primitive properties from an object, destructure them out and add only those to the dependency array. ```javascript const { baseUrl, timeout } = apiConfig; ``` ```javascript useEffect(() => { // ... use baseUrl, timeout }, [baseUrl, timeout]); ``` 2. **Memoize Objects/Arrays:** If the entire object/array is a dependency and is derived from stable values, use `useMemo` to memoize its creation. This ensures its reference remains stable across renders unless its own dependencies change. ```javascript const stableConfig = useMemo(() => ({ baseUrl: '/api', timeout: 5000 }), []); ``` ```javascript useEffect(() => { // ... use stableConfig }, [stableConfig]); ``` 3. **Memoize Functions:** For functions, use `useCallback` to prevent new function instances on every render, ensuring a stable reference for your dependency array. Understanding how JavaScript handles reference equality is key to mastering `useEffect` and writing performant React applications. What's your go-to strategy for managing complex `useEffect` dependencies? #React #ReactJS #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭: 𝐓𝐡𝐞 𝐅𝐨𝐮𝐧𝐝𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐀𝐩𝐩𝐬 Ever wondered how a simple click can change a whole webpage? That’s the magic of State. In React, useState is the most fundamental Hook you’ll use to bring your interfaces to life. 🔹 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞? It’s a Hook that allows you to add state to functional components. When the state changes, React automatically re-renders the component to reflect the new data. 🔹 𝐓𝐡𝐞 𝐒𝐲𝐧𝐭𝐚𝐱 const [state, setState] = useState(initialValue); -- state: The current value. -- setState: The function to update the value. -- initialValue: The starting point (number, string, etc.). 🔹 𝐒𝐢𝐦𝐩𝐥𝐞 𝐂𝐨𝐮𝐧𝐭𝐞𝐫 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>𝐂𝐨𝐮𝐧𝐭: {count}</h1> <button onClick={() => setCount(count + 1)}>𝐈𝐧𝐜𝐫𝐞𝐦𝐞𝐧𝐭</button> </div> ); } 🔹 𝐏𝐫𝐨 𝐓𝐢𝐩𝐬 𝐟𝐨𝐫 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 -- 𝐃𝐨𝐧'𝐭 𝐦𝐮𝐭𝐚𝐭𝐞 𝐬𝐭𝐚𝐭𝐞 𝐝𝐢𝐫𝐞𝐜𝐭𝐥𝐲: Never do count = count + 1. Always use the setter function (setCount). -- 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐍𝐚𝐭𝐮𝐫𝐞: State updates aren't immediate. Use functional updates if you need the previous state: setCount(prev => prev + 1). -- 𝐈𝐧𝐢𝐭𝐢𝐚𝐥 𝐑𝐞𝐧𝐝𝐞𝐫: The initial value is only used during the first render. 𝐖𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐨𝐬𝐭 𝐜𝐨𝐦𝐩𝐥𝐞𝐱 𝐬𝐭𝐚𝐭𝐞 𝐲𝐨𝐮’𝐯𝐞 𝐦𝐚𝐧𝐚𝐠𝐞𝐝 𝐢𝐧 𝐚 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭? Let’s discuss in the comments! 👇 Feel free to reach me out for any career mentoring Naveen .G.R|CareerByteCode #ReactJS #WebDevelopment #MERNStack #CodingTips #Javascript #Frontend
To view or add a comment, sign in
-
-
⚡ JavaScript Tip: Stop adding 100 event listeners. Use Event Delegation instead. One of the hottest (and smartest) patterns in the JavaScript world is Event Delegation — and honestly, once you get it, you’ll start using it everywhere. Here’s the idea 👇 Instead of attaching event listeners to every single child element, you attach ONE listener to the parent and let event bubbling do the magic. Why this is awesome: ✅ Works even when elements are dynamically added/removed ✅ Cleaner code ✅ Better performance ✅ Less debugging headaches Let’s say we have a list: <ul id="parent-list"> <li id="post-1">Item 1</li> <li id="post-2">Item 2</li> <li id="post-3">Item 3</li> <li id="post-4">Item 4</li> <li id="post-5">Item 5</li> <li id="post-6">Item 6</li> </ul> Instead of adding listeners to every <li>, we do this: document.getElementById("parent-list").addEventListener("click", function(e) { if (e.target && e.target.nodeName == "LI") { console.log("List item ", e.target.id.replace("post-", ""), " was clicked!"); } }); Boom 💥 One listener. Works for all current and future list items. You can even target specific elements like this: document.getElementById("myDiv").addEventListener("click", function(e) { if (e.target && e.target.matches("a.classA")) { console.log("Anchor element clicked!"); } }); This is one of those concepts that looks simple but seriously levels up how you handle DOM events. If you're building dynamic UIs (especially in React-like environments or large apps), understanding this is a game changer. #javascript #frontenddevelopment #webdevelopment #reactjs #codingtips #programming #softwaredevelopment #devcommunity
To view or add a comment, sign in
-
The 2026 Modern Frontend Developer Roadmap Feeling overwhelmed by the "JavaScript fatigue" or the endless stream of new frameworks? You’re not alone. The frontend landscape moves fast, but the secret to staying relevant isn't learning everything it’s learning the right things in the right order. I’ve put together this visual guide to help you navigate the journey from writing your first line of HTML to deploying production-ready applications. 📍 The Journey at a Glance: Stage 1: The Bedrock. Master HTML5, CSS3 (Flexbox/Grid), and Modern JavaScript (ES6+). Without these, frameworks are just magic boxes you don't understand. Stage 2: Version Control. Git isn't optional. Learn to branch, merge, and collaborate on GitHub early. Stage 3: The Ecosystem. Get comfortable with NPM/Yarn and build tools like Vite. Stage 4: Choose Your Path. React, Vue, or Angular? Pick one, master its lifecycle, and stick with it until you can build a full-scale app. Stage 5: Styling at Scale. Move beyond vanilla CSS with Tailwind CSS or Sass for professional, maintainable designs. Stage 6: Reliability. State management (Redux/Zustand) and Testing (Jest/Cypress) separate the hobbyists from the pros. Stage 7: Advanced Tooling. TypeScript is the industry standard for a reason. Combine it with an understanding of REST and GraphQL APIs. Stage 8: Deployment. It's not finished until it’s live. Master Vercel, Netlify, and the basics of CI/CD. 💡 My Advice: Don’t try to check every box in a week. Build projects at every stage. A "perfect" roadmap on paper is worth nothing compared to a "messy" project on GitHub. Which stage are you currently in? Or if you're a senior dev, what one tool would you add to this list? Let’s discuss in the comments! 👇 #WebDevelopment #Frontend #Coding #Programming #SoftwareEngineering #WebDevRoadmap #ReactJS #JavaScript #CareerGrowth
To view or add a comment, sign in
-
-
⚠️ One tricky thing in React that confused me at first: useEffect dependencies At first, I thought useEffect just runs magically. But the truth is very simple 👇 🧠 Think of useEffect like this: “React, run this code after render, and re‑run it only when I tell you to.” That “telling” happens through the dependency array. ✅ Examples (super simple) useEffect(() => { console.log("Runs once"); }, []); ➡️ Runs only when component mounts but for the below case useEffect(() => { console.log("Runs when count changes"); }, [count]); ➡️ Runs every time count changes 🚨 The tricky part If you use a variable inside useEffect but forget to add it as a dependency, React will use an old value (stale data). 🧠 Rule to remember: If you use it inside useEffect, it should be in the dependency array. Once I understood this, useEffect stopped feeling scary 😊 Just logic + clarity. #React #JavaScript #Hooks #useEffect #Frontend #LearningInPublic
To view or add a comment, sign in
-
Most React devs know the shorthand fragment syntax: <> </> Clean. No extra DOM nodes. Love it. But here's the catch. It doesn't accept props. So when you're mapping over a list and need to add a key, this won't work: posts?.map(post => ( <> <PostTitle title={post.title} /> <PostBody body={post.body} /> </> )) React needs that key to efficiently track and update list items. Without it, you'll get warnings and potential rendering bugs. The fix? Use the full Fragment syntax: import { Fragment } from 'react'; posts?.map(post => ( <Fragment key={post?.id}> <PostTitle title={post?.title} /> <PostBody body={post?.body} /> </Fragment> )) You get: No extra DOM wrapper Proper keys on list items Clean, valid JSX Small detail. Big difference in correctness. Save this for the next time you're mapping over data with multi-element rows. #React #JavaScript #Frontend #WebDev #ReactJS
To view or add a comment, sign in
-
Explore related topics
- Coding Best Practices to Reduce Developer Mistakes
- How to Achieve Clean Code Structure
- Clean Code Practices For Data Science Projects
- How To Prioritize Clean Code In Projects
- How Developers Use Composition in Programming
- Building Clean Code Habits for Developers
- Writing Functions That Are Easy To Read
- How to Improve Your Code Review Process
- How to Add Code Cleanup to Development Workflow
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