🔥 React Tip: Stop Using useEffect for Derived State🔥 Many developers reach for useEffect when they want to compute values based on props or state. This creates unnecessary re-renders and bugs. ❌ Don't do this: function Cart({ items }) { const [total, setTotal] = useState(0); useEffect(() => { setTotal(items.reduce((sum, item) => sum + item.price, 0)); }, [items]); return <div>Total: ${total}</div>; } ✅ Do this instead: function Cart({ items }) { const total = items.reduce((sum, item) => sum + item.price, 0); return <div>Total: ${total}</div>; } Why? → Eliminates an entire render cycle → No synchronization bugs → Simpler mental model → Better performance To improve performance, use memoization: function Cart({ items }) { const total = useMemo( () => items.reduce((sum, item) => sum + item.price, 0), [items] ); return <div>Total: ${total}</div>; } 💡 Rule of thumb: If you can calculate it during render, don't use useEffect to sync it into state. 𝗣𝗦: 𝗗𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗰𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗺𝗮𝘀𝘀𝗶𝘃𝗲 𝗼𝗳𝗳𝗲𝗿 𝗼𝗳 𝟵𝟯% 𝗱𝗶𝘀𝗰𝗼𝘂𝗻𝘁 𝗼𝗻 𝘁𝗵𝗲 𝗣𝗿𝗼 / 𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲 𝗦𝘂𝗯𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻. 𝗟𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝗮𝗻𝗱 𝗶𝗻 𝘁𝗵𝗲 𝗳𝗲𝗮𝘁𝘂𝗿𝗲𝗱 𝘀𝗲𝗰𝘁𝗶𝗼𝗻 𝗼𝗳 𝗺𝘆 𝗟𝗶𝗻𝗸𝗲𝗱𝗜𝗻 𝗽𝗿𝗼𝗳𝗶𝗹𝗲. #javascript #reactjs #nextjs #webdevelopment
Avoid Using useEffect for Derived State in React
More Relevant Posts
-
💡React Tip💡 You don't need to use debouncing every time during search or filtering. React 18's useTransition hook offers a more seamless way to manage them. ⚡ 𝗪𝗵𝘆 𝗶𝘁'𝘀 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹: → Keeps your UI responsive during heavy updates → No need for setTimeout or debounce libraries → Built-in priority system for React rendering → Perfect for search filters, data tables, and complex lists 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: When filtering large lists, every keystroke can freeze your UI because React tries to update everything immediately. 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: use useTransition hook from react. useTransition lets you mark certain updates as "low priority" so React can keep your UI smooth. In the code sample example, typing in the search box updates instantly (high priority), while filtering the huge list happens in the background (low priority) without blocking the input. The isPending flag tells you when the background work is still running, so you can show a loading indicator. 𝗞𝗲𝘆 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀: → Input stays responsive - no lag while typing → React automatically prioritizes user input over list updates → isPending gives you a loading state for free → Works seamlessly with Suspense boundaries 𝗖𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗦𝘁𝗮𝗰𝗸𝗯𝗹𝗶𝘁𝘇 𝗱𝗲𝗺𝗼 𝗹𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝘁𝗼 𝘀𝗲𝗲 𝗶𝘁 𝗶𝗻 𝗮𝗰𝘁𝗶𝗼𝗻. 𝘍𝘰𝘳 𝘮𝘰𝘳𝘦 𝘴𝘶𝘤𝘩 𝘶𝘴𝘦𝘧𝘶𝘭 𝘤𝘰𝘯𝘵𝘦𝘯𝘵, 𝘥𝘰𝘯'𝘵 𝘧𝘰𝘳𝘨𝘦𝘵 𝘵𝘰 𝘧𝘰𝘭𝘭𝘰𝘸 𝘮𝘦. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
-
💡 JavaScript Tip: The Magical length Property of Arrays 😎 Most developers know that array.length gives the number of elements… But do you know how powerful (and tricky) it actually is? Let’s explore 👇 --- 🔹 1. Length is not read-only const arr = [1, 2, 3, 4]; arr.length = 2; console.log(arr); // [1, 2] 👉 Setting length truncates the array! All elements beyond the new length are removed. --- 🔹 2. You can also extend the array const arr = [1, 2]; arr.length = 5; console.log(arr); // [1, 2, <3 empty items>] 👉 Empty slots are created (they’re not undefined, they’re missing). --- 🔹 3. Length doesn’t always mean “last index + 1” const arr = []; arr[5] = 42; console.log(arr.length); // 6 👉 Sparse arrays have holes — indexes 0 to 4 don’t exist, but length still counts the last index + 1. --- 🔹 4. Deleting items doesn’t reduce length const arr = [10, 20, 30]; delete arr[1]; console.log(arr.length); // 3 console.log(arr); // [10, <1 empty item>, 30] 👉 The hole remains — length ignores deletions! --- ⚡ Quick Recap: Operation Effect on length push() / unshift() Increases pop() / shift() Decreases delete arr[i] No change arr.length = n Trims or extends --- 💭 Takeaway: length is not just a property — it’s a controller of your array’s shape and size. Handle it carefully to avoid silent bugs! --- #JavaScript #WebDevelopment #Frontend #CodingTips #JSArrays
To view or add a comment, sign in
-
You think you know React... until you have to clean up a third-party script. I had a major "Aha!" moment building my Financial dashboard project, and it's a perfect example of how React's declarative world meets imperative, real-world JavaScript. The Problem: I'm integrating TradingView's embeddable widgets, which aren't React components. This requires manually creating <script> tags and injecting them into a div using a useEffect hook. The Naive Approach: Just create the script in useEffect and let React unmount the div when it's done. Simple, right? Wrong. This creates massive memory leaks. The third-party script (the "tenant") running inside my div (the "house") has its own background processes: setIntervals, WebSockets, and global event listeners. When React unmounts the div (demolishes the house), it doesn't tell the tenant to clean up. The "ghost" tenant lives on, still fetching data and consuming memory. The Solution & The "Aha!" Moments: 1. The "Stale Ref" Problem: My first attempt at a cleanup function failed because ref.current is null when the cleanup runs! The Fix: You have to snapshot the ref's value inside the effect: const node = ref.current;. The cleanup function's closure then remembers this node, even after ref.current is nullified. 2. The "Tenant Eviction" Model: This was the real lightbulb moment. Why clean the div with node.innerHTML = "" if React is removing it anyway? The Fix: The cleanup is not for React. It's a signal for the third-party script. Setting innerHTML = "" is like "evicting the tenant." The script is built to detect this, triggering its own internal destroy() logic—clearing its timers, closing its connections, and actually preventing the memory leak. Takeaway: React manages its own lifecycle, but we are 100% responsible for the lifecycle of any imperative, non-React code we introduce. This dive was a powerful lesson in JavaScript closures, React's lifecycle, and robust memory management. #reactjs #javascript #webdevelopment #frontend #MERNstack #reacthooks #memorymanagement #learning #coding
To view or add a comment, sign in
-
-
💡Today I got to know something new about React with key and index in .map() I have always encountered such a code when it comes to rendering lists in React Example: {items.map((item, index) => ( <div key={index}>{item.name}</div> ))} It works... though I came to know that accessing the index as a key can be a problem at times 🧠The actual action of the key prop: React employs key to monitor list items that can change, get removed, or added. This assists React in only updating what is necessary which enhances performance and maintains the UI uniformity. When it's fine to use index: The array index may be used safely as a key only in cases when: 1. The list does not change or rearrange. 2. The information is non- dynamic and can not be edited. Example: {colors.map((color, index) => ( <li key={index}>{color}</li> ))} It is perfect for simple lists that don’t change. When not to use index: If your list: 1. Reorders dynamically 2. Adds or removes items 3. Or state (as inputs or animations) of each item. Example: {users.map(user => ( <UserCard key={user.id} user={user} /> ))} Key takeaway: Index use should be restricted to non-changing lists that are never modifie This proved to be incredibly useful in getting to know the way React manages to re-render lists effectively. Have you ever encountered strange bugs due to the use of index as a key? React #Frontend #WebDevelopment #JavaScript #LearningInPublic.
To view or add a comment, sign in
-
Ever felt like debugging a slow UI update was like pouring water into a basket? We’ve all been there. We write some JS code, change some state, and suddenly our UI is sluggish. We instinctively blame the browser's "slowness." But what's really happening under the hood? React handles rendering in a way that might surprise some developers. React does not have its own magical rendering engine. React is just JavaScript running in a browser's JS engine (V8, SpiderMonkey, and so on). Every render and commit phase runs in the main thread's call stack. So how does React make complex UIs feel fast if it’s just running JS? Here’s the secret: - The "Virtual DOM" Blueprint: When the state changes, React first builds a virtual copy of the new UI in pure JS (the render phase). This is fast, as it doesn't touch the actual browser UI. - The Diffing Strategy: React then compares the new blueprint to the old one. It finds the minimal changes required to sync reality with the blueprint. - The Browser Handshake: React talks to the real browser rendering engine via standard DOM APIs. The key takeaway? React doesn't re-render the entire DOM tree every time (which would be expensive). It calculates the exact elements that need updating. This efficiency is why React feels so performant. It’s intelligent DOM manipulation. Understanding this architecture helps write better, faster code. #ReactJS #FrontendDevelopment #JavaScript #WebDev #Engineering #CareerGrowth #TechInsights
To view or add a comment, sign in
-
🤔 🚨 Ever seen [object Object] in your alert or log? 📌 Alert boxes can only show strings. When you pass an object like 👉 alert({name: 'Jane'}), the object gets converted to a string via toString(). Since no custom toString() is defined, it outputs [object Object]. 📌 Console log’s smarter display It usually shows an interactive object you can inspect in developer tools. But if you do : 👉 console.log("User: " + obj), it coerces obj to a string calling toString() and showing [object Object]. 📌 In short: [object Object] means JavaScript is using the default object-to-string conversion that’s not meant to show you the object’s details. #javascript #frontend #reactJS #angular
To view or add a comment, sign in
-
-
🚀 Deep Dive into React's useRef Hook: What, Why & How 🚀 After mastering React Fiber, reconciliation, useState, and useEffect, it’s essential to know useRef—a hook that often gets misunderstood but is incredibly powerful. What is useRef? useRef returns a mutable object with a .current property that persists across renders. Unlike useState, updating this value does NOT cause re-renders, making it perfect for storing mutable data that doesn’t affect UI. Behind the Scenes React keeps the same ref object between renders. Changing .current just updates the value without triggering React’s reconciliation or rendering process. This makes useRef ideal to: Reference DOM elements directly. Keep any mutable value (timers, counters, previous state) without UI updates. Why useRef when we have useState? useState triggers re-renders on state change. useRef doesn’t cause re-renders, giving performance benefits where UI updates aren’t needed. Great for tracking values that persist but don’t impact rendering. Common Misconceptions ❌ useRef is only for DOM references (No! It can hold any mutable data). ❌ Updating .current causes UI updates (No, only useState does). ❌ useRef replaces all state (No, it’s complementary; useState controls reactive state). Frequent Errors to Avoid Trying to access .current too early before DOM refs are assigned. Expecting UI to update on .current changes (use state for that). Reassigning the entire ref instead of updating .current. Using useRef when reactive state is needed. Final Thoughts useRef unlocks powerful capabilities: persistent storage within renders, DOM access, and optimization by avoiding unnecessary updates. Mastering it alongside useState and useEffect elevates your React component design and performance. Are you using useRef effectively in your projects? Share your experience or questions below! 👇 #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #ReactHooks #ProgrammingTips #SoftwareEngineering #WebDev #TechTips #ReactCommunity #CodingBestPractices
To view or add a comment, sign in
-
-
🌀 The useEffect Hook in React: The useEffect hook in React ⚛️ is used to handle side effects in functional components. Side effects are actions that affect something outside the scope of the current function — such as:🧱 updating the DOM, 🔄 setting up subscriptions, or ⏰ managing timers. 🧩 Purpose: It replaces old lifecycle methods like: 🏗️ componentDidMount 🔁 componentDidUpdate 🧹 componentWillUnmount from class components. 🧠 Syntax: useEffect(() => { // 🧾 Code to run return () => { // 🧹 Cleanup code }; }, [dependencies]); 📘 Parameters Explained: ➡️ Effect Function ⚙️ – Contains the main logic that performs the side effect (e.g., API call or DOM manipulation). ➡️ Cleanup Function 🧼 – An optional return function inside useEffect used to clean up resources such as event listeners or timers. ➡️ Dependency Array 🧮 – Determines when the effect should re-run. 🧭 How the Dependency Array Works: 🔹No dependency array → Runs after every render 🔁 🔹 Empty array [ ] → Runs once after the first render 🏁 🔹 Array with values [a, b] → Runs when any listed value changes ⚡ ✨ Quick Tip: 💡 Keep your effects clean and focused — split multiple side effects into separate useEffect hooks for better readability and performance. hashtag #React #Redux #Javascript #WebDevelopment #Frontend #LearnToCode #UI
To view or add a comment, sign in
-
⚛️ That moment when I just wanted to access an element... and React said “NO re-rendering allowed!” 😂 I was building a simple input box and needed to focus it when a button was clicked. Naturally, I thought: “Easy! I’ll use useState().” So I did something like this 👇 ❌ Before: function InputFocus() { const [input, setInput] = useState(null); const handleClick = () => { input.focus(); }; return ( <> <input ref={setInput} /> <button onClick={handleClick}>Focus</button> </> ); } And then React said: “Wait... you’re updating state just to get a DOM element?” 😩 That’s when I discovered useRef() — my quiet, reliable hook friend that doesn’t trigger re-renders. 🧘♂️ ✅ After using useRef(): function InputFocus() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleClick}>Focus</button> </> ); } 💡 Lesson learned: useRef() stores a mutable value that survives re-renders. Perfect for accessing DOM elements or saving values without causing updates. No unnecessary renders. No chaos. Just pure focus. 🎯 React hooks each have their own “superpower” — and useRef() is the stealthy one! 🦸♀️ #ReactJS #useRef #ReactHooks #FrontendDeveloper #MERNStack #WebDevelopment #LearningByDoing #JavaScript #ReactTips #CodingJourney
To view or add a comment, sign in
-
💡 A powerful (and often underrated) use case for useRef in React useRef isn’t just about accessing DOM elements — it quietly solves one of the most important problems in React: preserving mutable values across re-renders without triggering re-renders. A classic example is a stopwatch ⏱️ const timerRef = useRef(null); const start = () => { timerRef.current = setInterval(() => { setSeconds((s) => s + 1); }, 1000); }; const stop = () => { clearInterval(timerRef.current); }; If we used a normal variable like let timer, React would reset it to null after every re-render (since the component function runs again). The result? Your “Stop” button wouldn’t actually stop the timer — the interval would keep running in the background. useRef prevents that by giving you a stable place to store such values — perfect for things like: Intervals / timeouts WebSocket or media stream instances Storing previous values Keeping track of imperative API references It’s one of those hooks that doesn’t re-render the UI, but silently keeps your logic rock solid. ⚙️✨ Sometimes, the most powerful tools are the quiet ones. #ReactJS #FrontendDevelopment #WebDev #JavaScript #useRef
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