<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by sherry shad on Medium]]></title>
        <description><![CDATA[Stories by sherry shad on Medium]]></description>
        <link>https://medium.com/@sharareshaddev?source=rss-78c15fedac03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tLLcmwm1Wsq_GfMeaBsJ7Q.jpeg</url>
            <title>Stories by sherry shad on Medium</title>
            <link>https://medium.com/@sharareshaddev?source=rss-78c15fedac03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:57:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharareshaddev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Closures in React (With Real Examples)]]></title>
            <link>https://medium.com/@sharareshaddev/understanding-closures-in-react-with-real-examples-11e57e4b2ba6?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/11e57e4b2ba6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[clouser]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 07:36:39 GMT</pubDate>
            <atom:updated>2026-02-10T07:47:18.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7x2lcMh3kOSn6QOxWgNtUg.png" /></figure><p>If you’ve worked with React for a while, you’ve probably hit moments like:</p><ul><li>“Why is this state value always the old one?”</li><li>“Why does this setInterval never see updated data?”</li><li>“Why does my handler remember something that no longer exists?”</li></ul><p>And someone replied with:</p><blockquote>“That’s because of closures.”</blockquote><p>Cool.<br> But what does that actually mean <strong>in React</strong>?</p><p>Let’s break it down without theory overload.</p><h3>First: What Is a Closure?</h3><p>A <strong>closure</strong> happens when a function <em>remembers</em> the variables from the place where it was created — even after that place is gone.</p><p>In JavaScript:</p><pre>function outer() {<br>  let count = 0<br>return function inner() {<br>    console.log(count)<br>  }<br>}<br>const fn = outer()<br>fn() // logs 0</pre><p>Even though outer() has finished running, inner() still remembers count.</p><p>That memory = <strong>closure</strong>.</p><h3>Why Closures Matter So Much in React</h3><p>React is <strong>re-render based</strong>.</p><p>Every render:</p><ul><li>creates <strong>new variables</strong></li><li>creates <strong>new functions</strong></li><li>keeps <strong>old functions alive</strong> if something references them</li></ul><p>That’s where closures quietly sneak in.</p><h3>The Classic React Closure Bug</h3><p>Let’s look at something very common:</p><pre>function Counter() {<br>  const [count, setCount] = React.useState(0)<br><br>  React.useEffect(() =&gt; {<br>    const id = setInterval(() =&gt; {<br>      console.log(&#39;interval sees:&#39;, count)<br>    }, 1000)<br><br>    return () =&gt; clearInterval(id)<br>  }, [])<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      count: {count}<br>    &lt;/button&gt;<br>  )<br>}</pre><h3>What You Expect</h3><p>You click a button, count updates, and the console logs the latest value.</p><h3>What Actually Happens</h3><p>It logs <strong>0 forever</strong>.</p><p>Why?</p><h3>What Actually Happened</h3><ul><li>useEffect runs <strong>once</strong></li><li>The callback inside setInterval <strong>closes over</strong> the count value from the <strong>first render</strong></li><li>That value was 0</li><li>React re-renders, but the interval callback is still using the old closure</li></ul><p>React didn’t “lose” your state.Your function just <strong>remembered the past</strong>.</p><h3>Visualizing the Problem</h3><p>Think of it like this:</p><pre>Render #1:<br>  count = 0<br>  interval callback → remembers count = 0<br><br>Render #2:<br>  count = 1<br>  (interval callback still alive, still remembers count = 0)</pre><p>Closures don’t update themselves.</p><h3>Fix #1: Add Dependencies (Sometimes)</h3><pre>useEffect(() =&gt; {<br>  const id = setInterval(() =&gt; {<br>    console.log(count)<br>  }, 1000)<br><br>  return () =&gt; clearInterval(id)<br>}, [count])</pre><p>Now:</p><ul><li>Effect re-runs on every count change</li><li>Old interval is cleared</li><li>New closure captures the new count</li></ul><p>This works — <strong>but recreates the interval every time</strong>.</p><p>Sometimes fine. Sometimes not ideal.</p><h3>Fix #2: Functional State Updates (Best for State Changes)</h3><p>If your problem is updating state, not reading it:</p><pre>setCount(prev =&gt; prev + 1)</pre><p>This avoids closure issues because:</p><ul><li>React passes the <strong>latest value</strong></li><li>You’re not relying on a closed-over variable</li></ul><p>This is the <strong>most recommended fix</strong>.</p><h3>Fix #3: useRef to Escape Closures</h3><p>When you need <strong>always-fresh data</strong> without re-running effects:</p><pre>function Counter() {<br><br>  const [count, setCount] = React.useState(0)<br>  const countRef = React.useRef(count)<br><br>  React.useEffect(() =&gt; {<br>    countRef.current = count<br>  }, [count])<br><br>  React.useEffect(() =&gt; {<br>    const id = setInterval(() =&gt; {<br>      console.log(countRef.current)<br>    }, 1000)<br>    return () =&gt; clearInterval(id)<br>  }, [])<br><br>  return &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;{count}&lt;/button&gt;<br>}</pre><p>Here:</p><ul><li>ref is mutable</li><li>It doesn’t care about renders</li><li>The interval always reads the latest value</li></ul><p>This pattern is <strong>very common in advanced React</strong>.</p><h3>Closures and Event Handlers</h3><p>This one surprises people:</p><pre>function Example() {<br>  const [value, setValue] = React.useState(0)<br>    const handleClick = () =&gt; {<br>        setTimeout(() =&gt; {<br>          console.log(value)<br>        }, 2000)<br>      }<br>  return &lt;button onClick={handleClick}&gt;Click&lt;/button&gt;<br>}</pre><p>If value changes before 2 seconds pass, the log still prints the <strong>old value</strong>.</p><p>Same reason. Same closure.</p><h3>Important Mental Model</h3><blockquote><strong><em>Closures are not a React bug.<br> They are a JavaScript feature.<br> React just makes them visible.</em></strong></blockquote><p>Once you internalize this, React feels <em>predictable</em> instead of magical.</p><h3>When Closures Are Your Friend</h3><p>Closures aren’t bad. They’re powerful:</p><ul><li>Memoized callbacks (useCallback)</li><li>Custom hooks</li><li>Encapsulating logic</li><li>Preventing unnecessary recalculations</li></ul><p>The goal is not to avoid closures — <br> it’s to <strong>know when you’re relying on them</strong>.</p><h3>Final Takeaway</h3><p>If something in React feels “stuck in the past”, ask yourself:</p><ul><li>Where was this function <strong>created</strong>?</li><li>What variables did it <strong>close over</strong>?</li><li>Does it need <strong>fresh state</strong> or <strong>stable state</strong>?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e57e4b2ba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern CDN Invalidation Strategies for Dynamic SPA Content]]></title>
            <link>https://medium.com/@sharareshaddev/modern-cdn-invalidation-strategies-for-dynamic-spa-content-7c3081d2a0c5?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c3081d2a0c5</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cache-memory]]></category>
            <category><![CDATA[cdn-service]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Wed, 28 May 2025 09:29:13 GMT</pubDate>
            <atom:updated>2025-05-28T09:29:13.510Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Edge Caching in CDNs (Cloudflare, Akamai) and Purge On-Demand Techniques</strong></p><h4>Introduction</h4><p>In modern Single Page Application (SPA) architectures, where dynamic and static content coexist, managing edge caching and invalidation has become a critical challenge. Traditional CDNs were designed primarily for static content delivery, but in today’s dynamic web ecosystem, smart, selective, and on-demand cache invalidation is essential for both performance and content accuracy.</p><p>In this article, we’ll explore:</p><ul><li>How Edge Caching works in modern CDNs like Cloudflare and Akamai</li><li>Various invalidation methods</li><li>Pro-level Purge On-Demand strategies tailored for dynamic SPAs</li></ul><h4>Edge Caching in Modern CDNs</h4><p>Edge Caching means keeping a cached copy of assets at the nearest CDN edge node to the user, significantly reducing latency and improving perceived speed.</p><p>In modern CDNs:</p><ul><li><strong>Static Asset Caching</strong>: Based on cache-control headers (max-age, immutable)</li><li><strong>Dynamic Content Caching</strong>: Edge servers may cache content with low TTLs or bypass caching for sensitive content</li><li><strong>Custom Cache Keys</strong>: Define cache keys based on query strings, headers, or cookies to handle content variations</li></ul><h3>Purge On-Demand in SPA Architectures</h3><p>Since SPAs dynamically fetch data and render content asynchronously, it’s crucial to invalidate cached resources at the right time without compromising performance.</p><h4>📌 Effective Techniques:</h4><ul><li><strong>Cache-Tagging in Cloudflare</strong><br> Tag related assets (e.g., product pages) and purge them collectively when content changes<br> ➝ Fast and group-based invalidation</li><li><strong>Custom Cache Keys</strong><br> Define cache keys that include cookies or session data to handle private or personalized content<br> ➝ Prevents unintended shared caching</li><li><strong>API Cache-Control Headers</strong><br> Use Cache-Control: no-store or max-age=60, stale-while-revalidate=300<br> ➝ Ensures content freshness with fallback caching</li><li><strong>Invalidate via Webhooks</strong><br> Connect your backend systems (CMS, Admin Panel) to the CDN purge API<br> ➝ Automatically trigger purge when content updates</li></ul><h4>📌 Example:</h4><p>When a product is updated via CMS:</p><ol><li>CMS sends a webhook notification</li><li>Webhook handler triggers a CDN purge request for the relevant URL or cache tag</li></ol><h3>Best Practices</h3><p>✅Avoid long-term caching for index.html<br> ✅ Use <strong>asset hashing</strong> for JS and CSS files<br> ✅ Manage API responses with short TTLs or stale-while-revalidate<br> ✅ Leverage <strong>tag-based purge</strong> for dynamic content<br> ✅ Consider cookies and querystrings in your edge cache policies</p><h3>Conclusion</h3><p>In modern SPA ecosystems, cache management is a delicate balance between speed and content freshness. By combining advanced Purge On-Demand techniques and intelligent Edge Caching, you can ensure fast content delivery while maintaining data accuracy.</p><p>Both Cloudflare and Akamai provide powerful APIs and features to achieve this. Choosing the right invalidation strategy depends on your project’s specific caching and invalidation needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c3081d2a0c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Preload Errors: How to Properly Cache and Preload CSS & SCSS in SPAs]]></title>
            <link>https://medium.com/@sharareshaddev/stop-preload-errors-how-to-properly-cache-and-preload-css-scss-in-spas-6913b4978ad5?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/6913b4978ad5</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[preloading]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Sun, 11 May 2025 12:28:43 GMT</pubDate>
            <atom:updated>2025-05-11T12:28:43.784Z</atom:updated>
            <content:encoded><![CDATA[<p>In <strong>Single Page Applications (SPA)</strong>, proper cache management and preload handling for CSS and SCSS files are critical for ensuring <strong>good performance, deployment consistency, and a smooth user experience</strong>.</p><p>Unfortunately, many projects suffer from issues like:</p><ul><li>Preload errors in monitoring tools like Sentry</li><li>Old styles being loaded after new deployments</li><li>Users needing to hard-refresh the browser</li><li>Asset and frontend version mismatches</li></ul><p>This article will explain, in a clear and structured way, how to properly manage caching and preload for CSS and SCSS files in SPA projects.</p><h3>The Difference Between CSS and SCSS in Production</h3><p><strong>SCSS</strong>:</p><ul><li>Compiled into CSS during the build process (via tools like Vite or Webpack)</li><li>Never loaded directly in the browser</li><li>No caching or preload needed at runtime</li></ul><p><strong>CSS</strong>:</p><ul><li>The final output after build</li><li>In production, CSS files usually come in two types:</li></ul><p><strong>-Without a hash in the filename</strong> (e.g., /styles/main.css)</p><p><strong>-With a hash in the filename</strong> (e.g., /assets/main.abc123.css)</p><p><strong>Correct Cache-Control Policy for CSS Files</strong></p><h3>CSS without a hash</h3><p>These files should <strong>never be cached</strong> in the browser.<br> If cached, users may continue seeing old styles after a new deployment.</p><p><strong>Recommended header:</strong></p><pre>Cache-Control: no-cache</pre><p><strong>CSS with a hash in the filename</strong></p><p>These files have a unique name after each build (including a hash).<br> They are safe to cache <strong>permanently</strong> because when the content changes, the filename also changes.</p><p><strong>Recommended header:</strong></p><pre>Cache-Control: public, max-age=31536000, immutable</pre><p>The immutable directive tells browsers not to check for updates as long as the filename remains unchanged.</p><p>Preloading <strong>critical CSS</strong> can improve First Paint and Largest Contentful Paint (LCP) scores. But — in SPA projects with hashed filenames, you should not preload static, non-hashed file paths because:</p><ul><li>After build, a file like /src/assets/styles/main.scss turns into /assets/main-abc123.css</li><li>Static preload links pointing to the old path will cause preload errors (like Unable to preload CSS in Sentry)</li></ul><h3>Correct Solutions</h3><ul><li>Remove preload links from your index.html</li><li>OR dynamically inject preload links at runtime</li><li>OR use a build-time plugin like <a href="https://github.com/anncwb/vite-plugin-html">vite-plugin-html</a> to insert hashed filenames into preload links automatically</li></ul><h3>Versioning and Cache Busting for SPA</h3><p>To detect new deployments and notify users:</p><ol><li>Create a <strong>version.txt</strong> file during your build process</li><li>Set Cache-Control: no-cache for this file</li><li>Check the version value periodically in your SPA and prompt the user for a refresh if it changes</li></ol><h3>Summary</h3><p>In production:</p><ul><li><strong>SCSS is never loaded directly</strong></li><li><strong>Non-hashed CSS files should have no-cache</strong></li><li><strong>Hashed CSS files can use long-term cache with immutable</strong></li><li><strong>Preload only when your link matches the build output filename</strong></li><li><strong>Version your builds using a version file or meta tag in </strong><strong>index.html</strong></li></ul><p><strong>Thanks for reading!</strong><br> If you found this guide useful, consider sharing it with your team or bookmarking it for your next SPA deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6913b4978ad5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Tests as Documentation: A Frontend Developer’s Revelation]]></title>
            <link>https://medium.com/@sharareshaddev/unit-tests-as-documentation-a-frontend-developers-revelation-8411d2a53772?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/8411d2a53772</guid>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 14:27:50 GMT</pubDate>
            <atom:updated>2025-04-01T14:27:50.220Z</atom:updated>
            <content:encoded><![CDATA[<p>Why Do I Have to Write These Unit Tests? Oh Wait, They’re Actually Useful…</p><p>When my manager asked me to write unit tests for components in our Vue.js application, I was reluctant. Why spend time testing a button when I could be building new features? But as I dug deeper, I discovered that unit tests aren’t just for catching bugs —they’re living <strong>documentation </strong>that explains how your components work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*U8j9SFRkh9N5fykm3Ijz4g.png" /></figure><h3>How Unit Tests Document Your Components</h3><p>1. <strong>They describe expected behavior</strong>—tests outline what your component does, how it behaves with different inputs, and what outputs to expect.</p><p>2. <strong>They showcase use cases</strong>—tests demonstrate real examples of how to use your component in different scenarios</p><p>3. <strong>They explain component constraints</strong>—tests reveal the boundaries of your component: what it can and cannot do.</p><p>Let’s look at three real-world examples that demonstrate how unit tests serve as documentation</p><h3>Example 1: Documenting a Button Component</h3><pre>import { mount } from &#39;@vue/test-utils&#39;<br>import AppButton from &#39;@/components/AppButton.vue&#39;<br><br>describe(&#39;AppButton&#39;, () =&gt; {<br>  // Documents that the component renders different visual styles<br>  it(&#39;applies the correct class based on variant prop&#39;, () =&gt; {<br>    const variants = [&#39;primary&#39;, &#39;secondary&#39;, &#39;danger&#39;]<br>    <br>    variants.forEach(variant =&gt; {<br>      const wrapper = mount(AppButton, {<br>        props: { variant }<br>      })<br>      expect(wrapper.classes()).toContain(`btn-${variant}`)<br>    })<br>  })<br><br>  // Documents that the component supports different sizes<br>  it(&#39;applies the correct size class based on size prop&#39;, () =&gt; {<br>    const wrapper = mount(AppButton, {<br>      props: { size: &#39;large&#39; }<br>    })<br>    expect(wrapper.classes()).toContain(&#39;btn-large&#39;)<br>  })<br><br>  // Documents that the button emits a click event when clicked<br>  it(&#39;emits click event when clicked&#39;, async () =&gt; {<br>    const wrapper = mount(AppButton)<br>    await wrapper.trigger(&#39;click&#39;)<br>    expect(wrapper.emitted(&#39;click&#39;)).toBeTruthy()<br>  })<br><br>  // Documents that the button doesn&#39;t emit click events when disabled<br>  it(&#39;does not emit click event when disabled&#39;, async () =&gt; {<br>    const wrapper = mount(AppButton, {<br>      props: { disabled: true }<br>    })<br>    await wrapper.trigger(&#39;click&#39;)<br>    expect(wrapper.emitted(&#39;click&#39;)).toBeFalsy()<br>  })<br>})</pre><p>Anyone reading these tests immediately understands:</p><ul><li>The button supports different variants (primary, secondary, danger)</li><li>It can be rendered in different sizes</li><li>It emits a click event when clicked (unless disabled)</li><li>The disabled state prevents click events</li></ul><h3>Example 2: Documenting a Form Component</h3><pre>import { mount } from &#39;@vue/test-utils&#39;<br>import SignupForm from &#39;@/components/SignupForm.vue&#39;<br><br>describe(&#39;SignupForm&#39;, () =&gt; {<br>  // Documents required fields<br>  it(&#39;shows validation errors when submitted with empty fields&#39;, async () =&gt; {<br>    const wrapper = mount(SignupForm)<br>    await wrapper.find(&#39;form&#39;).trigger(&#39;submit&#39;)<br>    <br>    expect(wrapper.find(&#39;[data-test=&quot;email-error&quot;]&#39;).exists()).toBe(true)<br>    expect(wrapper.find(&#39;[data-test=&quot;password-error&quot;]&#39;).exists()).toBe(true)<br>  })<br><br>  // Documents email validation rules<br>  it(&#39;validates email format&#39;, async () =&gt; {<br>    const wrapper = mount(SignupForm)<br>    <br>    await wrapper.find(&#39;[data-test=&quot;email-input&quot;]&#39;).setValue(&#39;invalid-email&#39;)<br>    await wrapper.find(&#39;form&#39;).trigger(&#39;submit&#39;)<br>    <br>    expect(wrapper.find(&#39;[data-test=&quot;email-error&quot;]&#39;).text())<br>      .toContain(&#39;Please enter a valid email address&#39;)<br>  })<br><br>  // Documents password requirements<br>  it(&#39;validates password minimum length&#39;, async () =&gt; {<br>    const wrapper = mount(SignupForm)<br>    <br>    await wrapper.find(&#39;[data-test=&quot;password-input&quot;]&#39;).setValue(&#39;short&#39;)<br>    await wrapper.find(&#39;form&#39;).trigger(&#39;submit&#39;)<br>    <br>    expect(wrapper.find(&#39;[data-test=&quot;password-error&quot;]&#39;).text())<br>      .toContain(&#39;Password must be at least 8 characters&#39;)<br>  })<br><br>  // Documents successful submission behavior<br>  it(&#39;emits submit event with form data when valid&#39;, async () =&gt; {<br>    const wrapper = mount(SignupForm)<br>    const testUser = {<br>      email: &#39;test@example.com&#39;,<br>      password: &#39;password123&#39;<br>    }<br>    <br>    await wrapper.find(&#39;[data-test=&quot;email-input&quot;]&#39;).setValue(testUser.email)<br>    await wrapper.find(&#39;[data-test=&quot;password-input&quot;]&#39;).setValue(testUser.password)<br>    await wrapper.find(&#39;form&#39;).trigger(&#39;submit&#39;)<br>    <br>    expect(wrapper.emitted(&#39;submit&#39;)[0][0]).toEqual(testUser)<br>  })<br>})</pre><p>These tests clearly document:</p><ul><li>What fields are required</li><li>The specific validation rules for email</li><li>Password requirements</li><li>The format of data emitted on successful submission</li></ul><h3>Example 3: Documenting a Data Chart Component</h3><p>For a complex data visualization component like DataChart:</p><pre>import { mount } from &#39;@vue/test-utils&#39;<br>import DataChart from &#39;@/components/DataChart.vue&#39;<br><br>describe(&#39;DataChart&#39;, () =&gt; {<br>  const sampleData = [<br>    { month: &#39;Jan&#39;, value: 10 },<br>    { month: &#39;Feb&#39;, value: 20 },<br>    { month: &#39;Mar&#39;, value: 15 }<br>  ]<br><br>  // Documents expected data structure<br>  it(&#39;renders chart when valid data is provided&#39;, () =&gt; {<br>    const wrapper = mount(DataChart, {<br>      props: { data: sampleData }<br>    })<br>    <br>    expect(wrapper.find(&#39;.chart-container&#39;).exists()).toBe(true)<br>    expect(wrapper.findAll(&#39;.bar&#39;)).toHaveLength(3)<br>  })<br><br>  // Documents empty state handling<br>  it(&#39;displays a message when no data is provided&#39;, () =&gt; {<br>    const wrapper = mount(DataChart, {<br>      props: { data: [] }<br>    })<br>    <br>    expect(wrapper.find(&#39;.no-data-message&#39;).exists()).toBe(true)<br>    expect(wrapper.find(&#39;.no-data-message&#39;).text()).toContain(&#39;No data available&#39;)<br>  })<br><br>  // Documents how component handles loading state<br>  it(&#39;shows loading indicator when in loading state&#39;, () =&gt; {<br>    const wrapper = mount(DataChart, {<br>      props: { loading: true }<br>    })<br>    <br>    expect(wrapper.find(&#39;.loading-spinner&#39;).exists()).toBe(true)<br>    expect(wrapper.find(&#39;.chart-container&#39;).exists()).toBe(false)<br>  })<br><br>  // Documents responsive behavior<br>  it(&#39;adjusts chart height based on container prop&#39;, () =&gt; {<br>    const wrapper = mount(DataChart, {<br>      props: { <br>        data: sampleData,<br>        height: &#39;300px&#39;<br>      }<br>    })<br>    <br>    expect(wrapper.find(&#39;.chart-container&#39;).attributes(&#39;style&#39;))<br>      .toContain(&#39;height: 300px&#39;)<br>  })<br>})</pre><p>These tests document:</p><ul><li>The expected data structure for the chart</li><li>How the component handles edge cases (empty data, loading state)</li><li>Component customization options</li></ul><h3>Conclusion</h3><p>Unit tests aren’t just a quality assurance tool —they’re the most up-to-date documentation your code will ever have. Unlike comments or external documentation, tests can’t drift out of sync with your code because they’ll fail when the behavior changes.</p><p>The next time you’re tempted to skip writing tests to move on to new features, remember that you’re not just testing —you’re documenting your work for yourself and your team. Your future self (and your teammates) will thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8411d2a53772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Primitive and Reference Types in JavaScript]]></title>
            <link>https://medium.com/@sharareshaddev/understanding-primitive-and-reference-types-in-javascript-1994e307de0b?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/1994e307de0b</guid>
            <category><![CDATA[primitive-data-types]]></category>
            <category><![CDATA[reference-type]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Fri, 17 May 2024 07:30:56 GMT</pubDate>
            <atom:updated>2024-05-17T07:30:56.424Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re working with JavaScript, it’s super important to know the difference between primitive and reference types, and to understand what it means for data to be mutable or immutable. Let’s break it down in simple terms.</p><p><strong>Primitive Types<br></strong>Primitive types are basic data types that store their own value directly. These include:</p><pre>- Number: like 1, 2.5, 100<br>- String: like &quot;hello&quot;, &quot;123&quot;<br>- Boolean: true or false<br>- Null: a special value indicating an intentional absence of any object value<br>- Undefined: indicates a variable that has been declared but not assigned a value</pre><p>When you assign a primitive value to a variable, you are copying the value.</p><p>Example:</p><pre>let x = 10;<br>let y = x;<br>y = 20;<br>console.log(x); // 10<br>console.log(y); // 20</pre><p><strong>Reference Types<br></strong>Reference types, like objects (Objects) and arrays (Arrays), store a reference (or address) to where the data is kept in memory.</p><pre>let obj1 = { name: &quot;Ali&quot; };<br>let obj2 = obj1;<br>obj2.name = &quot;Reza&quot;;<br>console.log(obj1.name); // &quot;Reza&quot;<br>console.log(obj2.name); // &quot;Reza&quot;</pre><p><strong>What Does Mutable Mean?<br></strong>Mutable means that the data can be changed after it’s created. Objects, arrays, and functions in JavaScript are mutable.</p><pre>let person = { name: &quot;Ali&quot;, age: 25 };<br>person.name = &quot;Reza&quot;;<br>console.log(person); // { name: &quot;Reza&quot;, age: 25 }<br>// Example with an Array:<br><br>let numbers = [1, 2, 3];<br>numbers.push(4);<br>console.log(numbers); // [1, 2, 3, 4]</pre><p><strong>What Does Immutable Mean?</strong><br>Immutable means that the data cannot be changed once it’s created. Primitive types like numbers, strings, and booleans are immutable.</p><p>Example with a String:</p><pre>let greeting = &quot;Hello&quot;;<br>let newGreeting = greeting.replace(&quot;H&quot;, &quot;J&quot;);<br>console.log(greeting); // &quot;Hello&quot;<br>console.log(newGreeting); // &quot;Jello&quot;</pre><p><strong>Why Is This Important?</strong><br>- <strong>Memory Management</strong>: Mutable data helps optimize memory usage because changes are made directly to the original data.</p><p><strong>Practical Tip:</strong><br>When working with objects and arrays, changes in one variable can affect another if they reference the same data. To avoid this, you can use a deep copy.</p><pre>#### Deep Copy of an Object:<br>```javascript<br>let original = { name: &quot;Ali&quot;, age: 25 };<br>let copy = JSON.parse(JSON.stringify(original));<br>copy.name = &quot;Reza&quot;;<br>console.log(original); // { name: &quot;Ali&quot;, age: 25 }<br>console.log(copy); // { name: &quot;Reza&quot;, age: 25 }</pre><p>With a deep copy, you create a completely independent copy of the original object, so changes to the copy won’t affect the original.</p><p>— -</p><p>By understanding these concepts, you can write better code and avoid potential issues. What do you think about this? Share your thoughts and experiences!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1994e307de0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Primitive Type, Reference Type , Mutable , Immutable]]></title>
            <link>https://medium.com/@sharareshaddev/primitive-type-reference-type-mutable-immutable-caec75b27b5a?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/caec75b27b5a</guid>
            <category><![CDATA[جاوا-اسکریپت]]></category>
            <category><![CDATA[primitive-data-types]]></category>
            <category><![CDATA[reference-type]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Fri, 17 May 2024 07:24:26 GMT</pubDate>
            <atom:updated>2024-05-17T07:25:00.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>Primitive Type, Reference Type , Mutable , Immutable</h3><p><strong>تفاوت‌های Primitive Type و Reference Type در جاوااسکریپت</strong></p><p>در برنامه‌نویسی با جاوااسکریپت، آشنایی با تفاوت‌های بین نوع‌های داده‌ای primitive و reference و همچنین مفهوم mutable و immutable بودن داده‌ها می‌تواند به بهبود کیفیت کد و جلوگیری از باگ‌های احتمالی کمک کند. بیایید به زبان ساده این مفاهیم را بررسی کنیم.</p><p><strong>نوع‌های Primitive</strong></p><p>این تایپ ها شامل داده‌های ساده و پایه‌ای هستن که مستقیماً مقدار خود را نگه می‌دارن. این نوع‌ها شامل موارد زیر هستند:Number , string , Boolean , null , undefined, symbol</p><p>حالا نکته اش چیه ؟</p><p>وقتی یک مقدار از نوع primitive را به یک متغیر دیگر اختصاص می‌دیم، یک <strong>کپی</strong> از آن مقدار ایجاد می‌شود.</p><p>مثال:</p><pre>let x = 10;let y = x;y = 20;console.log(x); // 10console.log(y); // 20</pre><p><strong>Reference types :</strong></p><p>این تایپ ها شامل آبجکت‌ها (Objects) و آرایه‌ها (Arrays) هستند و به <strong>جای نگه داشتن مقدار واقعی، یک آدرس یا اشاره‌گر به مکانی از حافظه که داده در آن ذخیره شده را نگه می‌دارند</strong>.</p><p>مثال:</p><pre>let obj1 = { name: &quot;Ali&quot; };let obj2 = obj1;obj2.name = &quot;Reza&quot;;console.log(obj1.name); // &quot;Reza&quot;console.log(obj2.name); // &quot;Reza&quot;`</pre><p><strong>Mutable (قابل تغییر) چیست؟</strong></p><p>داده‌های mutable قابل تغییر هستند، یعنی پس از ایجاد می‌توانیم مقادیر یا خصوصیات آن‌ها را تغییر دهیم. آبجکت‌ها (Objects)، آرایه‌ها (Arrays) و توابع (Functions) نمونه‌هایی از داده‌های mutable هستند.</p><p>مثال آبجکت:</p><pre>let person = { name: &quot;Ali&quot;, age: 25 };person.name = &quot;Reza&quot;;console.log(person); // { name: &quot;Reza&quot;, age: 25 }</pre><p>مثال آرایه:</p><pre>let numbers = [1, 2, 3];numbers.push(4);console.log(numbers); // [1, 2, 3, 4]</pre><p><strong>Immutable (غیر قابل تغییر) چیست؟</strong></p><p><strong>Primitive types</strong> مانند عددها (Numbers)، رشته‌ها (Strings) و بولین‌ها (Booleans) غیر قابل تغییر هستند. به این معنا که وقتی یک مقدار جدید به متغیری اختصاص می‌دهیم، یک متغیر جدید با مقدار جدید ایجاد می‌شود و<strong> مقدار قبلی</strong> تغییر نمی‌کند.</p><p>مثال رشته:</p><pre>let greeting = &quot;Hello&quot;;let newGreeting = greeting.replace(&quot;H&quot;, &quot;J&quot;);console.log(greeting); // &quot;Hello&quot;console.log(newGreeting); // &quot;Jello&quot;</pre><p>چرا این موضوع مهمه؟</p><p>- <strong>کنترل حافظه</strong>: داده‌های mutable به بهینه‌سازی استفاده از حافظه کمک می‌کننن زیرا تغییرات بر روی همان نسخه اصلی اعمال می‌شه.</p><p><strong>نکته کاربردی:</strong></p><p>هنگام کار با آبجکت‌ها و آرایه‌ها، تغییرات در یک متغیر می‌تواند بر متغیرهای دیگر که به همان آبجکت یا آرایه اشاره می‌کنند، تأثیر بگذارد. برای جلوگیری از این مشکل، می‌تونید از دیپ کپی(Deep Copy) استفاده کنید:</p><pre>let original = { name: &quot;Ali&quot;, age: 25 };let copy = JSON.parse(JSON.stringify(original));copy.name = &quot;Reza&quot;;console.log(original); // { name: &quot;Ali&quot;, age: 25 }console.log(copy); // { name: &quot;Reza&quot;, age: 25 }</pre><p>با استفاده از این روش، یک کپی کاملاً مستقل از آبجکت اصلی ایجاد می‌شود و تغییرات در کپی بر آبجکت اصلی تأثیری ندارد.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caec75b27b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Differences Between Map and Object in JavaScript]]></title>
            <link>https://medium.com/@sharareshaddev/understanding-the-differences-between-map-and-object-in-javascript-b92e7cf8fa6c?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92e7cf8fa6c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 13:15:51 GMT</pubDate>
            <atom:updated>2024-03-09T13:15:51.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*p8jesXlMXpW_YKIXMUH-KA.png" /></figure><p>Hello everyone 👋</p><p>As a front-end developer, I frequently deal with different JavaScript data structures to efficiently handle and arrange data. After learning about <a href="https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md">Object injection attacks</a> recently, I became interested in finding ways to reduce the security concerns associated with using Objects.</p><p>Map and Object are two frequently used structures, each with a unique set of features and applications. In order to provide a secure development environment, we will examine the differences between Map and Object in this article and discuss defenses against Object injection threats.</p><h3>Object:</h3><p>The Object, a longstanding feature in JavaScript, is a collection of key-value pairs restricted to string or symbol keys, inheriting properties and methods from its <strong>prototype</strong>. For instance, consider an Object storing user information:</p><pre>const user = {<br>  name: &#39;John Doe&#39;,<br>  age: 25,<br>  email: &#39;john@example.com&#39;,<br>};<br><br>user[&#39;__proto__&#39;].isAdmin = true;<br><br>console.log(user.isAdmin); </pre><h3>Map:</h3><p>On the other hand, the Map, introduced with ECMAScript 6, offers a more flexible alternative, supporting keys of any data type and <strong>avoiding the pitfalls of prototype chain manipulation</strong>. Consider a Map securely storing user information:</p><pre>const userMap = new Map([<br>  [&#39;name&#39;, &#39;John Doe&#39;],<br>  [&#39;age&#39;, 25],<br>  [&#39;email&#39;, &#39;john@example.com&#39;],<br>]);<br><br>userMap.set(&#39;__proto__&#39;, { isAdmin: true });<br><br>console.log(userMap.get(&#39;__proto__&#39;)); </pre><h3>Map vs. Object:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*fr-Dlacy8h-luQHaDwASUQ.png" /></figure><p>1. <strong>Object</strong>:</p><ul><li>Objects in JavaScript are collections of key-value pairs.</li><li>Keys are always <em>strings</em> or <em>symbols</em>, and values can be of any data type.</li><li>Objects have a prototype chain, which means they inherit properties and methods from their prototype.</li></ul><p>2. <strong>Map</strong>:</p><ul><li>Maps, introduced in ECMAScript 6, are also collections of key-value pairs.</li><li>Keys can be of <em>any data type</em>, including objects or primitive values.</li><li>Maps <strong>do not have</strong> a prototype chain, providing a clean slate for storing key-value pairs.</li></ul><h3>When to Use Map Instead of Object</h3><p>It all comes down to the particular requirements in your code as to when in JavaScript to utilize a Map rather than an Object. Map is your best option if you want to be flexible with the kinds of keys you employ because it supports more than just strings and symbols like Objects. Maps are more secure in terms of security since they lack a complex prototype chain that attackers could exploit. Because of this, Maps are a superior option for managing key-value pairs that users supply, avoiding possible security problems.</p><p>Furthermore, unlike Objects, where the order is not guaranteed, Maps ensure a predictable order based on insertion, which is helpful if maintaining the order of key-value pairs is important.</p><h3>Examples of Map</h3><p>Here are some additional examples illustrating different use cases for Maps:</p><pre>1. Storing Complex Data:<br><br>const personMap = new Map();<br>personMap.set(&#39;name&#39;, &#39;Alice&#39;);<br>personMap.set(&#39;age&#39;, 30);<br>personMap.set(&#39;address&#39;, { city: &#39;Wonderland&#39;, country: &#39;Fantasia&#39; });<br><br>// Retrieving values<br>console.log(personMap.get(&#39;name&#39;)); // Alice<br>console.log(personMap.get(&#39;address&#39;).city); // Wonderland<br><br></pre><pre>2. Iterating Through Key-Value Pairs:<br><br>const fruitMap = new Map([<br>  [&#39;apple&#39;, 3],<br>  [&#39;banana&#39;, 5],<br>  [&#39;orange&#39;, 2]<br>]);<br><br>// Using forEach for iteration<br>fruitMap.forEach((value, key) =&gt; {<br>  console.log(`${key} quantity: ${value}`);<br>});<br><br>// Output:<br>// apple quantity: 3<br>// banana quantity: 5<br>// orange quantity: 2</pre><pre>3. Handling Dynamic Key Names:<br><br>// Using a Map to store dynamic key-value pairs<br>const dynamicMap = new Map();<br><br>const key1 = { name: &#39;KeyOne&#39; };<br>const key2 = { name: &#39;KeyTwo&#39; };<br><br>dynamicMap.set(key1, &#39;Value One&#39;);<br>dynamicMap.set(key2, &#39;Value Two&#39;);<br><br>console.log(dynamicMap.get(key1)); // Value One<br>console.log(dynamicMap.get(key2)); // Value Two</pre><pre>4. Checking for Key Existence:<br><br><br>// Using a Map to check for the existence of a key<br>const carMap = new Map([<br>  [&#39;make&#39;, &#39;Toyota&#39;],<br>  [&#39;model&#39;, &#39;Camry&#39;],<br>  [&#39;year&#39;, 2020]<br>]);<br><br>// Checking if a key exists<br>console.log(carMap.has(&#39;model&#39;)); // true<br>console.log(carMap.has(&#39;color&#39;)); // false</pre><h3><strong>In conclusion</strong></h3><p>There are uses for both Map and Object in JavaScript development. Using Map is frequently a better choice when working with an expanded amount of data and seeking a safer solution to avoid prototype chain problems. On the other hand, objects work well in simpler contexts where key types are restricted to strings or symbols and the prototype chain is not an issue. Front-end developers are better able to make judgments depending on the needs of their projects when they are aware of these distinctions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92e7cf8fa6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why You Shouldn’t Mess with the DOM manipulation in Your React App]]></title>
            <link>https://medium.com/@sharareshaddev/why-you-shouldnt-mess-with-the-dom-manipulation-in-your-react-app-fdd6483da43c?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdd6483da43c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 12:25:41 GMT</pubDate>
            <atom:updated>2023-12-02T12:25:41.252Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re in the world of React, building your web app with its intricate, behind-the-scenes magic. Now, think about stumbling upon something unexpected — someone messing directly with the website’s building blocks, known as the DOM. It’s like finding someone trying to fix a car engine with a hammer when there are proper tools available. Why would someone do that when React is there to handle things smoothly? This raises a question — is this a harmless quirk, or could it lead to a web development mystery?</p><p>🔍 Join me as we dig into the story of direct DOM tweaks in a React realm, exploring if it’s a harmless surprise or a potential plot twist in our coding adventure.</p><h3>The Unwanted Shortcut 🛑</h3><p>Let’s explore an example where direct DOM manipulation in a React app could lead to potential issues:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>const IncorrectDomManipulationExample = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const button = document.getElementById(&#39;increment-button&#39;);<br><br>    if (button) {<br>      button.addEventListener(&#39;click&#39;, () =&gt; {<br>        setCount(count + 1); // Incorrectly manipulating state directly<br>      });<br>    }<br><br>    return () =&gt; {<br>      // Removing event listener to avoid memory leaks<br>      button.removeEventListener(&#39;click&#39;, () =&gt; {<br>        setCount(count + 1);<br>      });<br>    };<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Incorrect DOM Manipulation Example&lt;/h2&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button id=&quot;increment-button&quot;&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this example, instead of using React’s state management, the code attempts to take a shortcut by directly manipulating the state when the “Increment” button is clicked.</p><h3>The Issues Unveiled 🕵️‍♂️</h3><h4>1. Skipping React’s Toolbox 🧰:</h4><p>React’s strength lies in its toolbox, including the Virtual DOM. Direct DOM manipulation skips these tools, potentially causing rendering issues and performance problems.</p><h4>2. State Management Confusion 🤷‍♂️:</h4><p>The setCount function is called directly within the event listener. This confuses React&#39;s state management, leading to inconsistencies between the actual state and what&#39;s displayed on the UI.</p><h4>3. Cleanup Complications 🚧:</h4><p>Manually adding and removing event listeners is error-prone. Forgetting to remove an event listener can result in memory leaks and degraded performance over time.</p><h4>4. Readability and Maintenance Hurdles 📜:</h4><p>Direct DOM manipulation makes the code less readable and maintainable. It deviates from React’s clear structure, making it harder for developers to understand and modify the codebase.</p><h4>5. Compatibility Concerns 🔄:</h4><p>Direct DOM manipulation might not play well with future React updates or third-party libraries. Bypassing React’s intended mechanisms increases the risk of compatibility issues.</p><h3>The React Way: Leveraging State and Event Handling ✅</h3><p>Instead of taking risky shortcuts with direct DOM manipulation, it’s recommended to stick to React’s state and event handling capabilities. Here’s a corrected version of the example using React’s state management:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const CorrectDomManipulationExample = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const handleIncrement = () =&gt; {<br>    setCount(count + 1); // Correctly updating state<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Correct DOM Manipulation Example&lt;/h2&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={handleIncrement}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>By embracing React’s way of handling state and events, you ensure a more reliable and maintainable codebase. The virtual DOM will efficiently manage updates, aligning with React’s principles for a smoother development experience. ✨💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd6483da43c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Debouncing]]></title>
            <link>https://medium.com/@sharareshaddev/mastering-react-debouncing-f557586e9568?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/f557586e9568</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[debouncing]]></category>
            <category><![CDATA[debouncing-in-react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 12:23:33 GMT</pubDate>
            <atom:updated>2023-11-13T12:23:33.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*mS5-x-3aMlIZ3HqFzD2Omg.png" /></figure><h3>What is Debouncing? 🤔</h3><p>Debouncing is a technique used to control the frequency of a function’s execution. In the context of React, it’s often employed to manage input events like keystrokes or resizing, ensuring that the associated functions aren’t called too frequently, preventing performance bottlenecks. Imagine a light switch — you don’t need to flick it rapidly for the light to turn on or off!</p><h3>Why Use Debouncing in React? 🚥</h3><p>Consider a search bar where users input search queries. Without debouncing, every keystroke triggers an API call, leading to unnecessary requests and potential overloading. With debouncing, you can delay the execution of the search function until the user pauses typing, enhancing performance and efficiency.</p><h3>Let’s Get Hands-On! 👩‍💻👨‍💻</h3><h3>Step 1: Set Up Your React App</h3><p>If you haven’t already, create a new React app using create-react-app:</p><pre>npx create-react-app debouncing-demo<br>cd debouncing-demo<br>npm start</pre><h3>Step 2: Install Lodash</h3><p>We’ll use Lodash’s debounce function, a popular utility library for React:</p><pre>npm install lodash</pre><h3>Step 3: Implement Debouncing</h3><p>Open your component file (e.g., src/App.js) and set up a basic input and a function to be debounced:</p><pre>import React, { useState } from &#39;react&#39;;<br>import _ from &#39;lodash&#39;;<br><br>const App = () =&gt; {<br>  const [searchTerm, setSearchTerm] = useState(&#39;&#39;);<br><br>  const debouncedSearch = _.debounce((term) =&gt; {<br>    // Your search logic (e.g., API call) goes here<br>    console.log(`Searching for: ${term}`);<br>  }, 500); // Adjust the delay according to your needs (here, it&#39;s 500 milliseconds)<br><br>  const handleInputChange = (event) =&gt; {<br>    const { value } = event.target;<br>    setSearchTerm(value);<br>    debouncedSearch(value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Debouncing Demo&lt;/h1&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Search...&quot;<br>        value={searchTerm}<br>        onChange={handleInputChange}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h3>Step 4: Test Your Debounced Search</h3><p>Run your app (npm start) and open it in your browser. Open the console, and as you type in the search input, you&#39;ll notice that the Searching for: message appears only after a pause in typing. 🎉</p><p>Let’s explore another practical example of React debouncing. Imagine you have a resizable window, and you want to perform some action only after the user has finished resizing. Let’s create a simple app to demonstrate this scenario.</p><h3>Step 1: Create a New Component</h3><p>Create a new file, ResizableBox.js, for our resizable box component:</p><pre>// ResizableBox.js<br>import React, { useState } from &#39;react&#39;;<br>import _ from &#39;lodash&#39;;<br><br>const ResizableBox = () =&gt; {<br>  const [boxSize, setBoxSize] = useState({ width: 200, height: 100 });<br><br>  const debouncedResize = _.debounce(() =&gt; {<br>    // Your resize logic goes here<br>    console.log(&#39;Box resized!&#39;, boxSize);<br>  }, 500); // Adjust the delay according to your needs (here, it&#39;s 500 milliseconds)<br><br>  const handleResize = (event) =&gt; {<br>    const { clientWidth, clientHeight } = event.target;<br>    setBoxSize({ width: clientWidth, height: clientHeight });<br>    debouncedResize();<br>  };<br><br>  return (<br>    &lt;div<br>      style={{<br>        width: boxSize.width + &#39;px&#39;,<br>        height: boxSize.height + &#39;px&#39;,<br>        backgroundColor: &#39;lightblue&#39;,<br>        border: &#39;1px solid blue&#39;,<br>        resize: &#39;both&#39;,<br>        overflow: &#39;auto&#39;,<br>      }}<br>      onResize={handleResize}<br>    &gt;<br>      Resize me!<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ResizableBox;</pre><h3>Step 2: Integrate the Component</h3><p>Now, integrate this component into your main App.js:</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import ResizableBox from &#39;./ResizableBox&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Debouncing Demo&lt;/h1&gt;<br>      &lt;ResizableBox /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h3>Step 3: Test Resizing</h3><p>Run your app (npm start) and open it in your browser. You&#39;ll see a resizable box. As you resize it, the &quot;Box resized!&quot; message will only appear after a pause in resizing, thanks to the debouncing technique. 📏</p><p>And for the last one, lets’ explore another scenario where debouncing in React can be beneficial. Imagine you have a live search feature that fetches data from an API as the user types. To avoid sending a request for every keystroke, you can use debouncing. Let’s create a simple app for this:</p><h3>Step 1: Create a New Component</h3><p>Create a new file, LiveSearch.js, for our live search component:</p><pre>// LiveSearch.js<br>import React, { useState } from &#39;react&#39;;<br>import _ from &#39;lodash&#39;;<br><br>const LiveSearch = () =&gt; {<br>  const [searchTerm, setSearchTerm] = useState(&#39;&#39;);<br>  const [searchResults, setSearchResults] = useState([]);<br><br>  const debouncedSearch = _.debounce(async (term) =&gt; {<br>    // Simulate API call (replace with actual API call)<br>    const fakeAPICall = new Promise((resolve) =&gt; {<br>      setTimeout(() =&gt; {<br>        resolve(`Search results for: ${term}`);<br>      }, 1000); // Simulating a 1-second API response time<br>    });<br><br>    const result = await fakeAPICall;<br>    setSearchResults([result]);<br>  }, 500); // Adjust the delay according to your needs (here, it&#39;s 500 milliseconds)<br><br>  const handleInputChange = (event) =&gt; {<br>    const { value } = event.target;<br>    setSearchTerm(value);<br>    debouncedSearch(value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Live Search&lt;/h2&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Search...&quot;<br>        value={searchTerm}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;div&gt;<br>        {searchResults.map((result, index) =&gt; (<br>          &lt;p key={index}&gt;{result}&lt;/p&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default LiveSearch;</pre><h3>Step 2: Integrate the Component</h3><p>Now, integrate this component into your main App.js:</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import LiveSearch from &#39;./LiveSearch&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Debouncing Demo&lt;/h1&gt;<br>      &lt;LiveSearch /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h3>Step 3: Test Live Search</h3><p>Run your app (npm start) and open it in your browser. As you type in the search input, the &quot;Search results for:&quot; message will appear, but it will only do so after a pause in typing, thanks to the debouncing. This helps in reducing the number of API calls and ensures a smoother user experience. 🕵️‍♂️</p><h3>When to Avoid Debouncing 🚫</h3><h3>1. Button Clicks 💡:</h3><p>In situations where a button click triggers a critical action, such as form submissions or other user interactions, introducing a debounce delay may hinder the immediate responsiveness expected from the UI.</p><h3>2. Real-Time Data Updates 📈:</h3><p>For applications requiring real-time data updates, like live data visualizations or online gaming, debouncing may introduce delays that are detrimental to the user experience.</p><h3>3. Animations and Transitions 🎥:</h3><p>When working with animations or transitions, debouncing might disrupt the timing and smoothness of these visual effects. Immediate execution of functions is crucial for maintaining visual integrity.</p><h3>4. UI State Synchronization 🔄:</h3><p>Complex UI state updates that depend on intermediate states between debounced calls may not benefit from debouncing. In such cases, consider alternative strategies for handling state updates with precision.</p><h3>5. Throttling for Frequent Events 🐢:</h3><p>For frequent but lightweight events like mouse movements, throttling might be a more suitable alternative to debouncing. Throttling balances responsiveness and performance.</p><h3>Wrapping Up 🎁</h3><p>As you embark on your React journey, mastering debouncing is a valuable skill. However, it’s equally important to recognize scenarios where debouncing might not be the optimal choice. By understanding these nuances, you’ll be better equipped to make informed decisions in your React projects. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f557586e9568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop using personal names as git branches!]]></title>
            <link>https://medium.com/@sharareshaddev/stop-using-personal-names-as-git-branches-f75012693adf?source=rss-78c15fedac03------2</link>
            <guid isPermaLink="false">https://medium.com/p/f75012693adf</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[git-best-practices]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-branching]]></category>
            <dc:creator><![CDATA[sherry shad]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 13:32:04 GMT</pubDate>
            <atom:updated>2023-11-11T13:32:04.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there 👋 Ever noticed the trend of using personal names as Git branches? 🤔 Let’s talk about why that might not be the best idea and explore some alternatives to keep things organized and fun! 🌈</p><h3>Overview:</h3><p>In my experiences collaborating with various teams, I’ve spotted a common habit: folks using<em> personal names</em> as Git branch labels. While it might seem cozy initially, this approach can lead to a whirlwind of challenges.</p><p>🌪️ Let’s spice up our Git game with some alternative branch-naming strategies for a smoother and more joyful collaborative workflow! 🎉</p><h3>Tips for Better Git Branch Naming:</h3><h4>Use Separators for Readability:</h4><p>Craft branch names with separators like hyphens (-) or slashes (/) to boost readability. Consistency is key for a naming structure that’s as harmonious as your favorite song!</p><p><strong>Example:</strong></p><ul><li>Good: feature-user-authentication</li><li>Better: feature/user/authentication</li></ul><h4>Start with a Category Word:</h4><p>Start branch names with a category word to set the tone for the task. 🎉 Categories such as hotfix, bugfix, and feature can be the lively themes!</p><p>Examples:</p><ul><li>hotfix: Swift resolutions for critical issues.</li><li>bugfix: Addressing and fixing bugs.</li><li>feature: Adding, removing, or modifying a React feature.</li><li>test: Experimenting with non-issue tasks.</li><li>wip: Work in progress.</li></ul><h4>Utilize Issue ID:</h4><p>Add the ID of the related issue to the branch name for some extra flair in task identification and progress tracking.</p><ul><li>Example: wip-123-implement-redux-store - It&#39;s like telling a story; this branch is all about bringing Redux magic related to issue 123!</li></ul><h4>Include Author’s Name:</h4><p>Spice things up by adding the author’s name in a cool format like author-category-task. Get ready for some personalized and organized coding adventures!</p><ul><li>Example: jane.doe-feature-navbar - Jane&#39;s got the spotlight on updates to the navbar! 🚀</li></ul><p>Let’s dive into some front-end project scenarios and bring these tips to life with real examples!</p><p><strong>Hotfix:</strong></p><p>Branch Name: hotfix-navigation-bar</p><ul><li>Description: Quickly resolving a critical issue in the navigation bar that is causing application crashes. 🚑</li></ul><p><strong>Bugfix</strong>:</p><p>Branch Name: bugfix-form-validation</p><ul><li>Description: Addressing and fixing a bug related to form validation that allows users to submit incomplete data. 🐛</li></ul><p><strong>Feature</strong>:</p><p>Branch Name: feature-dark-mode</p><ul><li>Description: Adding a new feature to the React app that introduces a dark mode for better user experience. 🌙</li></ul><p><strong>Test</strong>:</p><p>Branch Name: test-api-integration</p><ul><li>Description: Experimenting with the integration of a new API to test its compatibility and functionality within the React app. 🧪</li></ul><p><strong>WIP (Work in Progress):</strong></p><p>Branch Name: wip-345-dashboard-redesign</p><ul><li>Description: A work-in-progress branch aimed at redesigning the dashboard, related to issue 345. 🚧</li></ul><h3>More Tips:</h3><p>-Avoid Numbers Only:</p><ul><li>Say no to branches named just with numbers! Instead, combine issue IDs with descriptive keywords for clarity.</li></ul><p>-Keep Branch Names Concise:</p><ul><li>While being informative is cool, keep those branch names short and sweet. Lengthy names might steal the spotlight from your awesome code!</li></ul><p>-Prioritize Consistency:</p><ul><li>Consistency is like the secret sauce! Stick to your chosen naming convention throughout your React project for a codebase that dances to the same beat. 💃</li></ul><h3>Conclusion:</h3><p>In the grand finale, adopting these Git branch-naming practices for your project is like hosting a fabulous coding party! 🎉 Your codebase will thank you with clarity, effective progress tracking, and smoother collaboration. Remember, consistency is key for a successful and maintainable repository.🚀✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f75012693adf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>