Read down below for the full Explination : 1. array.sort() → array.toSorted() ❌ array.sort() Mutates (changes) the original array Can cause hidden bugs in React state Not immutable-friendly ✅ array.toSorted() Returns a new sorted array Keeps original array untouched Safer for modern functional patterns 👉 In React, immutability = predictable UI. 2. JSON.parse(JSON.stringify(obj)) → structuredClone(obj) ❌ JSON trick Breaks Dates Breaks Maps/Sets Removes functions Fails with circular references ✅ structuredClone() Deep clones properly Supports complex data types Cleaner and faster 👉 Stop using the “hack”. Use the real API. 3. Promise.all() → Promise.allSettled() ❌ Promise.all() Fails immediately if ONE promise fails You lose other results ✅ Promise.allSettled() Waits for ALL promises Returns success + failure results Perfect for dashboards, multiple API calls 👉 More resilient apps. 4. indexOf() → findIndex() ❌ indexOf(value) Only works for exact matches Doesn’t work well with objects ✅ findIndex(callback) Can search with logic Works with objects More flexible Example: users.findIndex(user => user.id === 10) 👉 Cleaner + more expressive. #JavaScript #ModernJavaScript #WebDevelopment #FrontendDevelopment #CleanCode #ReactJS #SoftwareEngineering
Improve JavaScript Code with array.toSorted() and structuredClone()
More Relevant Posts
-
⚠️ This “clean” React code is a silent production bug. {data.length > 0 && data.map(...)} Looks fine in dev. Breaks in production. 💥 Here’s what actually goes wrong: ❌ data = undefined → crash ❌ data.length = 0 → renders “0” on UI 😳 ❌ No safety checks → unpredictable bugs 👉 What you should update: ✅ Replace short-circuit (&&) with ternary ✅ Add optional chaining → data?.map(...) ✅ Validate data → Array.isArray(data) ✅ Always add fallback UI ✅ Use proper keys (not index) 💡 Real example: Your API is slow → data is undefined → user sees a broken screen. 👉 Lesson: Clean code is not enough. Production-safe code is what matters. 💻 Check Image to understand much better and follow for more tips and learning 👨💻✍️ #ReactJS #Frontend #SoftwareEngineering #JavaScript #DevTips #Learning
To view or add a comment, sign in
-
-
🚨 Your API is fast… so why is your UI still slow? This is where most engineers get it wrong. They spend hours optimizing: Database queries Backend latency API response time And ignore what happens after the data arrives. --- 👉 The real issue: Main Thread Blocking Your browser runs most of your JavaScript on a single thread. That means: Rendering Event handling JS execution …all compete for the same resource. --- 🔴 What causes UI lag: Large JSON parsing Heavy loops on big datasets Complex state updates (especially in frameworks) Synchronous blocking operations Even a 200–300ms block can cause: 👉 Frame drops 👉 Input lag 👉 Janky scrolling --- 🟢 What high-performance apps do: 1. Break long tasks setTimeout(() => processChunk(data), 0); 2. Use requestIdleCallback Run non-critical work when browser is idle 3. Move heavy work off the main thread Web Workers 4. Optimize rendering frequency Batch state updates Avoid unnecessary re-renders --- ⚡ Real mindset shift: Stop asking: > “How fast is my API?” Start asking: > “How long is my main thread blocked?” --- 💡 Pro tip: Open Chrome DevTools → Performance tab Record a session If you see long tasks (>50ms): 👉 That’s your bottleneck. --- 🚀 Impact when you fix this: Smooth scrolling Instant click response Better perceived performance --- Most developers optimize the backend. Great developers optimize the user experience timeline. Where is your bottleneck right now? #frontend #performance #javascript #webdev #engineering
To view or add a comment, sign in
-
-
I used to get confused when I changed a variable in my code, but nothing happened on the screen. In React, I learned that you don't just change data—you have to manage the State. Today, I’m documenting how to give components "memory" using the useState hook. It’s the difference between a static page and an interface that actually reacts to the user. Here is how I’m thinking about it now: 1) State is Memory: Unlike normal variables that reset every time a component runs, state variables stay. When state changes, React "reacts" and updates the UI. 2) The Hook (useState): I’m using this tool to handle memory. It gives me the current value and a specific function—the "setter"—which is the only way to change that value. 3) The "Bell" (Re-rendering): I learned that you should never change state directly. You have to use the setter function. It’s like ringing a bell to tell React, "Hey, I changed something, please update the screen!" I'm still learning the ropes, but mastering state is what allows me to build anything from a simple counter to a complex dashboard. Tomorrow, I'm diving into how to handle "side effects" like fetching data with useEffect! Quick question: What was the first thing you built once you understood useState? For me, it was a classic counter! #CodeWithWajid #ReactJS #WebDevelopment #30DaysOfCode #LearningToCode #BuildingInPublic #Frontend #StateManagement
To view or add a comment, sign in
-
🚀 From Zero to Frontend – Part 8 Why Some Data Takes Time to Load (Async/Await Explained) Have you ever noticed a loading spinner on a website? That happens because data doesn’t arrive instantly. JavaScript handles this using asynchronous programming. Instead of blocking everything, it waits for results in the background. Modern syntax looks like this: JavaScript async function getUsers() { const response = await fetch("https://lnkd.in/gngWUK98"); const data = await response.json(); console.log(data); } What’s happening? • async allows asynchronous behavior • await pauses execution until data is ready • The UI stays responsive Without async/await: Apps would freeze Users would get frustrated Experience would break Understanding async/await helped me understand how real-world apps manage time and data. Next → Let’s talk about something many developers ignore: Event Bubbling. #JavaScript #AsyncAwait #FrontendDeveloper #WebDevelopment
To view or add a comment, sign in
-
-
Topic: Lifting State Up – The Secret to Syncing Components 🔼 Lifting State Up – The Secret to Syncing React Components Ever had two components that need the same data but their states go out of sync? 🤯 That’s where Lifting State Up saves you. 🔹 The Problem Two sibling components manage their own state → inconsistent UI. 🔹 The Solution Move the shared state to their closest common parent. const [value, setValue] = useState(""); Now the parent controls the data and passes it down as props 👇 ✔ Single source of truth ✔ Consistent UI ✔ Easier debugging 🔹 Real-World Example Search bar + Filter panel Both need the same query → keep state in parent. 💡 Golden Rule If multiple components need the same data, that state shouldn’t live in just one of them. 📌 React works best with unidirectional data flow. 📸 Daily React tips & visuals: 👉 https://lnkd.in/g7QgUPWX 💬 When did lifting state up finally “click” for you? 👍 Like | 🔁 Repost | 💭 Comment #React #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactTips #DeveloperLife
To view or add a comment, sign in
-
Day 12: useEffect Hook in React If useState handles data, then useEffect handles side effects. Understanding this hook is key to building real-world React applications. 📌 What is useEffect? useEffect is a React Hook used to perform side effects in functional components. Side effects include: • API calls • Fetching data • Updating the DOM • Setting up subscriptions • Timers (setInterval, setTimeout) 📌 Basic Syntax useEffect(() => { // side effect code }, [dependencies]); 📌 Example: Run on Component Mount import { useEffect } from "react"; function App() { useEffect(() => { console.log("Component Mounted"); }, []); return <h1>Hello React</h1>; } 👉 Empty dependency array [] means it runs only once (like componentDidMount). 📌 Example: Run on State Change import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log("Count changed:", count); }, [count]); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); } 👉 Runs every time count changes. 📌 Cleanup Function (Very Important) useEffect(() => { const interval = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(interval); }, []); 👉 Prevents memory leaks by cleaning up effects. 📌 Why useEffect is powerful ✅ Handles API calls ✅ Syncs UI with data ✅ Manages lifecycle in functional components ✅ Keeps code clean and organized #ReactJS #useEffect #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
Logic Over Frameworks! 🌐 Headline: Why I built a Console-Based API Manager (Logic First!) 🚀 Most developers focus on making things "look pretty" with CSS. I decided to do the opposite. I built a DataBridge API Manager that runs entirely in the Browser Console. Why Console-Based? Because I wanted to master Data Architecture and Asynchronous Logic without the distraction of UI frameworks. If the logic is solid in the console, the UI is just a "skin." Technical Highlights (The "Engine" under the hood):- ✅ Fast Data Loading: I used Promise.all to fetch Posts and Comments at the same time. This makes the app much faster than fetching them one by one. ✅ Smart Syncing: When I update or delete a post on the server, my code automatically updates the "Local Array" (the data in the browser) using the Spread Operator and Array Methods. No page refresh needed! ✅ Recycle Bin Logic: I built a "Trash" system. When you delete a post, it isn't gone forever—it moves to a Trash Bin, and I wrote logic to Restore it back to the main list. ✅ Professional Error Handling: I implemented try-catch blocks and status checks to make sure the app never crashes, even if the internet is slow. My focus is 100% on Skills. I am solving 30-50 logic problems every day to build "coding muscle memory." I’m getting closer to my MERN Stack goal every single day. Logic first, everything else second! 🔗 GitHub Repository: https://lnkd.in/gKCdnf3s 🔗 GitHub: https: https://lnkd.in/gDKWSymf #JavaScript #WebDevelopment #CodingJourney #LogicBuilding #MERNStack #Programming #SelfTaught #CleanCode
To view or add a comment, sign in
-
-
🚨 Why your React component re-renders (even when nothing changes) A lot of times we feel like: “Nothing changed… but my component re-rendered.” Actually, React always has a reason. Here are the real triggers 👇 🔁 What causes re-renders? • State change (useState) • Parent component re-render • Context value change • Props reference change ⚠️ The most ignored one: Reference change React does NOT check deep values. It only checks references. So even if data looks same, React treats it as new. Example: const obj = { name: "Dhana" }; This creates a new object every time → new reference → re-render ❌ Common mistake <MyComponent data={{ name: "Dhana" }} /> Looks fine, but this creates a new object on every render. ✅ Better way const data = useMemo(() => ({ name: "Dhana" }), []); <MyComponent data={data} /> Now reference stays same → no unnecessary re-render Don’t overuse useMemo/useCallback. Use them only when: 👉 re-renders are actually causing performance issues Understanding this one concept can level up your React skills a lot. #ReactJS #Frontend #WebDevelopment #JavaScript #Performance
To view or add a comment, sign in
-
⚠️ A Common React Mistake That Slowly Breaks Applications One thing I keep noticing in many React codebases: Everything becomes global state. At first it feels convenient. Need the data somewhere? Just put it in global state. But over time this starts causing problems: • Components re-render more than necessary • Debugging becomes harder • State dependencies become unclear • Performance slowly degrades Not every piece of data needs to live globally. Sometimes the best architecture is simply: ✅ Local state where possible ✅ Lift state only when necessary ✅ Global state only for truly shared data Frontend architecture isn’t about adding tools. It’s about using the right level of complexity for the problem. Sometimes the best optimization is simply keeping state closer to where it belongs. Curious how others approach this — How do you decide what belongs in global state vs local state? #ReactJS #FrontendDevelopment #JavaScript #SoftwareEngineering #WebDevelopment
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