<?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 Kanwal Shariq on Medium]]></title>
        <description><![CDATA[Stories by Kanwal Shariq on Medium]]></description>
        <link>https://medium.com/@offbeatgs?source=rss-24b7dabc37d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QqCUQRLbN7sJ_F32awEKhA.jpeg</url>
            <title>Stories by Kanwal Shariq on Medium</title>
            <link>https://medium.com/@offbeatgs?source=rss-24b7dabc37d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:51:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@offbeatgs/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[Why AI taking over creativity is not the same as AI taking over tech]]></title>
            <link>https://medium.com/@offbeatgs/why-ai-taking-over-creativity-is-not-the-same-as-ai-taking-over-tech-bdcc2eac71ae?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdcc2eac71ae</guid>
            <category><![CDATA[arts-and-culture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[human-creativity]]></category>
            <category><![CDATA[ai-takeover]]></category>
            <category><![CDATA[studio-ghibli]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 15:19:17 GMT</pubDate>
            <atom:updated>2025-04-04T15:19:43.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgeLpWV0rJMBGou6WA1i-A.png" /></figure><p>We all know what this is about.</p><p>Recently, there has been an uproar over AI generated pictures mimicking Ghibli’s hand drawn animations, with one side claiming it is just for fun and the other side pointing out that it is ethically wrong. Here, I’ll explain why the arguments the “fun” side are putting out are wrong and why humanity is doomed to fail if we let this happen (no, seriously).</p><h4>Comparing this uproar to previous protests over technological advancements</h4><p>I have seen people compare this to the printing press protests when the printer was invented, or the workers in the factory once automated machines took over, or when chatGPT could code better than software engineers. I am here to tell you that is not the same thing.</p><p>Technological advancement is crucial for the sake of progress. Humanity has always progressed, solving things one at a time, accomplishing feats that would have been impossible 100 years prior. Automation is required so humans can up-skill themselves and work towards new goals, new problems and come up with solutions faster. I am a software engineer myself, and yes, I know my job is not secured, but I am happy that AI can take up my redundant tasks so I can learn more, advance more. It is the same is other fields as well. Doctors, chemists, scientists, researchers, we all can use AI to progress, to find a cure for cancer for example, to find ways to tackle global warming, to automate more things that can make a difference in people’s lives.</p><h4><strong>Why AI and our hobbies should be separated</strong></h4><p>There is quite a famous quote by Joanna Maciejewsk:</p><blockquote>I want AI to do my laundry and dishes so that I can do art and writing, not for AI to do my art and writing so that I can do my laundry and dishes.</blockquote><p>If AI continues as it is, I would like you to imagine the consequences. A few years from now, say you have some free time. You sit down in the sun and wonder what you can do. Read a book written by AI? Listen to podcasts by AI? Watch a tv show made by AI? Listen to songs sung by AI? Consume content created by AI? Look at pictures taken by AI? You will rarely have any chance to see creations by mankind. You won’t be able to draw, write or create because you will know AI does it better so why bother?</p><p>There is a reason that humanity has come so far in technology while creativity has remained the same and that is what used to be the crux of our life. To see paintings of the old and new, different styles, perhaps different mediums but having the same soul and passion. To read books written years ago and finding subtle differences in writing styles, grammar and punctuations as compared to new books. To see digital art and still seeing the soul of it because a human created it with passion. To watching animations that took years to be created. All this is fundamentally the essence of our lives. Take creativity and our hobbies away and who are we? Why are we here? What is our purpose? We will end up as robots instead. The irony.</p><p>The point being, who asked for AI to take over our hobbies? We were fine with AI taking over our jobs, because that has always been inevitable but take away our hobbies and what are we left with? Take away the very thing that heals us and what will we become? Will art museums become history museums? Will books written by humans become vintage classics?</p><p>Artists will cease to exist, and so will their art.</p><h4>When did we consent for AI to be trained on our data?</h4><p>When did we? When did Studio Ghibli authorize for its animations to be used to train an AI model? When did any of us consent for our data to be used to train AI? We did not, and they still went ahead and used our data. Used our search histories, our codes, our videos, our pictures, our books, our songs without our consent and presented us with AI generated replicas of our work. There needs to be strict copy right laws to protect our data from being used to train AI without our consent. AI is now a part of every application, every system we use and it is continuing to use our data to better itself. Even this article I am writing right now is being used to train it.</p><p>In a world where we don’t own anything anymore, and everything is as subscription, the very least we can do is protect and own our data and identity.</p><h4><strong>Quite literally hurting the planet</strong></h4><p>My last point. It takes a vast amount of resources in the data centre to handle the demand of AI generated pictures. Millions, perhaps billions of users are trying out this trend and it is costing the openAI GPUs. What will they do to cope? Use practices that are not environment friendly and get materials for cheap from forced labour in underprivileged countries because that is what all the top tech companies have been doing for years. And no one stops them.</p><p>I hope something changes in the next few days, weeks or months because we are looking at the start of the end of human creativity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdcc2eac71ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimise API Calls in React Using Cache and Service Workers]]></title>
            <link>https://medium.com/@offbeatgs/optimise-api-calls-in-react-using-cache-and-service-workers-f7db2a4f5549?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7db2a4f5549</guid>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[api-call]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 16:06:26 GMT</pubDate>
            <atom:updated>2024-10-10T16:06:26.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wanted to minimise the API calls when you know the data has not changed, but still avoid storing the data directly on the client-side? Or, access data even if your app is offline? Well, caching can help with that! In this blog, I’ll guide you through implementing a very simple cache storage and retrieval using service workers in a React App with detailed explanation.</p><p><em>You will learn how to:</em></p><ol><li><em>Develop a service worker that fetches data from an API and stores it in cache.</em></li><li><em>Display data from cache instead of making a network call</em></li><li><em>Sets a limit to holding stale data, and fetches new data from API timely.</em></li><li><em>Debug with DevTools</em></li></ol><p>Let’s use a dummy JSON API, to fetch and store data. We will use <a href="https://dummyjson.com/recipes"><strong>https://dummyjson.com/recipes</strong></a> to get the list of recipes. We can have a simple dropdown through which users can select recipes, which will call the API <a href="https://dummyjson.com/recipes/$%7BrecipeId"><strong>https://dummyjson.com/recipes/recipeId</strong></a><strong>,</strong>and the details of the selected recipe will be shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFPdcyS2spJnXkebVdqlWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0acdq7-bJsbXdQrv3_iJw.png" /></figure><p>Let’s start from the basics.</p><h3>Create a react app</h3><pre>npx create-react-app service-worker<br>cd service-worker</pre><p>We have two <strong>actions</strong>. One is to fetch the list of recipes, the other to fetch specific recipe details. The react component will talk with the service worker using post message. Since service workers run independently, using postMessage lets the page and the service worker communicate without being tightly coupled using events. The flow of the app:</p><ul><li><strong>Component Sends Message to Service Worker</strong>: when the web page is loaded, and the service worker is ready, the web page sends a message using postMessage to request data or an action.</li><li><strong>Service Worker Processes the Message</strong>: the service worker receives the message, handles the action, caches the response, and sends a message back to the web page with the result.</li><li><strong>Page Receives Response</strong>: the web page listens for responses from the service worker and processes them.</li></ul><p>The actions: <strong>FETCH_RECIPES_LIST</strong> and <strong>FETCH_RECIPE_DETAILS</strong>.</p><h3>Create a service worker</h3><p>Create a file in the public folder with the name <strong>service-worker.js</strong>. Declare the cache name, API URL that you want to intercept and max expiration time for the cache.</p><p><strong>Note</strong>: For this project, we will be setting the expiration to one day. After one day, it make a network call to fetch new details and store updated data in cache.</p><pre>const CACHE_NAME = &#39;recipes-cache&#39;;<br>const API_URL_PREFIX = &#39;https://dummyjson.com/recipes&#39;;<br>const CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1000;</pre><p>Next, you need to install the service worker.</p><pre>// Install event: Open the cache<br>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then(() =&gt; {<br>      console.log(&#39;Cache opened&#39;);<br>    })<br>  );<br>});</pre><p><strong>Explanation:</strong></p><p>The install event listener in your service worker is where you typically define actions that should happen when the service worker is first installed. This often involves pre-caching essential resources that your app might need to function offline or load faster on subsequent visits.</p><p><strong>When does the </strong><strong>install event run?</strong></p><ul><li><strong>First Time</strong>: The install event is triggered the first time the service worker is registered.</li><li><strong>Updates</strong>: The install event is triggered again if you update or change the service worker script (e.g., change cache names or add new functionality).</li></ul><p><strong>Example</strong>:</p><pre>const urlsToCache = [<br>  &#39;/&#39;,<br>  &#39;/styles/main.css&#39;,<br>  &#39;/scripts/main.js&#39;,<br>  &#39;/recipes&#39; // Example API call or page<br>];<br><br>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      console.log(&#39;Opened cache&#39;);<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});</pre><p>Let’s write our main function. This will be responsible for fetching the API data, storing it in cache and cleaning up the cache.</p><pre>/* <br>* Makes the API call<br>* Stores response in cache<br>* Calls function to clean up cache<br>*/<br>async function fetchWithCache(url, event, type) {<br>  try {<br>    const response = await fetch(url, {<br>      headers: {<br>        &#39;Cache-Control&#39;: &#39;max-age=3600, stale-while-revalidate=86400&#39;, // Cache for 1 hour, revalidate in background for 1 day<br>      },<br>    });<br><br>    if (!response.ok) {<br>      throw new Error(`Network response was not ok: ${response.statusText}`);<br>    }<br><br>    const data = await response.json();<br>    //Send the data back to component<br>    event.source.postMessage({ type, data });<br><br>    //Store the data in cache<br>    const cache = await caches.open(CACHE_NAME);<br>    cache.put(url, new Response(JSON.stringify(data)));<br><br>    // Clean up old cache entries<br>    cleanUpCache(cache);<br><br>  } catch (error) {<br>    console.error(&#39;Fetch error:&#39;, error);<br>    event.source.postMessage({ error: &#39;Failed to fetch data.&#39; });<br>  }<br>}<br><br>/* <br>* Cleans up stale cache entries based on expiration<br>*/<br>async function cleanUpCache(cache) {<br>  const keys = await cache.keys();<br>  keys.forEach(async (request) =&gt; {<br>    const cachedResponse = await cache.match(request);<br>    const dateHeader = cachedResponse?.headers.get(&#39;Date&#39;);<br><br>    if (dateHeader &amp;&amp; new Date(dateHeader).getTime() + CACHE_EXPIRATION_MS &lt; Date.now()) {<br>      await cache.delete(request);<br>      console.log(`Deleted stale cache: ${request.url}`);<br>    }<br>  });<br>}</pre><p><strong>It is important to understand different options for Cache-Control.</strong></p><ul><li>Cache-Control: no-cache forces the browser to <strong>always validate the cached response</strong> with the server before using it. If the API data you’re fetching changes frequently, and you want to ensure you’re getting the most up-to-date data, no-cache is suitable. If the data is fairly static and doesn’t change often, no-cache is likely overkill because it can slow things down.</li><li>Cache-Control: max-age=3600 tells the browser that the response can be used for 1 hour before it should check the server for updates. You should use this if the data is updated at known intervals (e.g., once per hour or once per day) and you can tolerate serving slightly stale data between updates.</li><li>Cache-Control: max-age=3600, stale-while-revalidate=86400 allows you to serve the cached response while fetching a fresh one in the background. This is ideal for improving perceived performance while ensuring data is eventually updated.</li><li>Cache-Control: immutable this tells the browser that the response will never change. The browser can cache it indefinitely until the cache is manually cleared.</li></ul><p>We have used Cache-Control: max-age=3600, stale-while-revalidate=86400 which will provide the following benefits:</p><ul><li><strong>Immediate performance</strong>: If the data is cached and still fresh (within 1 hour), it’s served from the cache without contacting the server.</li><li><strong>Graceful updates</strong>: If the cache is older than 1 hour but less than 1 day, the cached data is served while the fresh data is fetched in the background, making the app feel fast.</li><li><strong>Data freshness</strong>: After 1 day, the data is re-fetched from the server.</li></ul><p>Let’s write a function that returns cached response:</p><pre>/*<br>* Returns cache response if url matches<br>* Checks if the cache entry is expired, returns null if expired or no match<br>*/<br>async function getCachedResponse(url) {<br>  const cache = await caches.open(CACHE_NAME);<br>  const cachedResponse = await cache.match(url);<br><br>  if (cachedResponse) {<br>    const dateHeader = cachedResponse.headers.get(&#39;Date&#39;);<br>    if (dateHeader &amp;&amp; new Date(dateHeader).getTime() + CACHE_EXPIRATION_MS &lt; Date.now()) {<br>      console.log(`Cache expired for ${url}`);<br>      await cache.delete(url);<br>      return null;<br>    }<br><br>    return cachedResponse.json();<br>  }<br><br>  return null;<br>}</pre><p>Our main event listener will listen to two actions we described above. It will first try to get it from the cache, if the cache is not available, it will fetch it from the network call.</p><pre>// Message event: Handle requests from the app<br>self.addEventListener(&#39;message&#39;, async (event) =&gt; {<br>  const { type, recipeId } = event.data;<br><br>  try {<br>    if (type === &#39;FETCH_RECIPES_LIST&#39;) {<br>      const cachedList = await getCachedResponse(`${API_URL_PREFIX}?select=name`);<br>      if (cachedList) {<br>        event.source.postMessage({ type: &#39;RECIPES_LIST&#39;, data: cachedList });<br>      } else {<br>        fetchWithCache(`${API_URL_PREFIX}?select=name`, event, &#39;RECIPES_LIST&#39;);<br>      }<br>    }<br><br>    if (type === &#39;FETCH_RECIPE_DETAILS&#39; &amp;&amp; recipeId) {<br>      const cachedRecipe = await getCachedResponse(`${API_URL_PREFIX}/${recipeId}`);<br>      if (cachedRecipe) {<br>        event.source.postMessage({ type: &#39;RECIPE_DETAILS&#39;, data: cachedRecipe });<br>      } else {<br>        fetchWithCache(`${API_URL_PREFIX}/${recipeId}`, event, &#39;RECIPE_DETAILS&#39;);<br>      }<br>    }<br>  } catch (error) {<br>    event.source.postMessage({ error: &#39;Error fetching data from network or cache.&#39; });<br>  }<br>});</pre><h3>Register the service worker</h3><p>Create a file in /src by the name of <strong>serviceWorkerRegistration.js</strong></p><pre>export function register() {<br>    if (&#39;serviceWorker&#39; in navigator) {<br>      window.addEventListener(&#39;load&#39;, () =&gt; {<br>        navigator.serviceWorker<br>          .register(&#39;/service-worker.js&#39;)<br>          .then((registration) =&gt; {<br>            console.log(&#39;Service worker registered:&#39;, registration);<br>          })<br>          .catch((error) =&gt; {<br>            console.log(&#39;Service worker registration failed:&#39;, error);<br>          });<br>      });<br>    }<br>  }<br>  <br>  export function unregister() {<br>    if (&#39;serviceWorker&#39; in navigator) {<br>      navigator.serviceWorker.ready.then((registration) =&gt; {<br>        registration.unregister();<br>      });<br>    }<br>  }</pre><p>On window load, the service worker will be registered.</p><p><strong>Explanation:</strong></p><p>The navigator is a built-in JavaScript object that represents the state and identity of the user agent (usually the browser).</p><ul><li><strong>navigator.serviceWorker</strong>: allows you to manage service workers, such as registering, unregistering, and getting information about the current service worker.</li><li><strong>navigator.serviceWorker.controller</strong>: returns the active service worker controlling the page, if one exists. It is null if there is no active service worker. If a service worker is controlling the page, the page’s fetch requests can be intercepted and handled by that service worker.</li><li><strong>if (‘serviceWorker’ in navigator)</strong>: This check is to ensure that the browser supports service workers. Not all browsers support service workers, so this is a safety check to prevent errors.</li></ul><p>We have also written a function to unregister the worker if that is in your use case or you need to test new features. You can call this function manually if need be or make it a part of the window load listener (Depending on your use case).</p><p><strong>Example</strong>:</p><pre>import * as serviceWorkerRegistration from &#39;./serviceWorkerRegistration&#39;;<br>  function App() {<br>   const handleUnregister = () =&gt; {<br>     serviceWorkerRegistration.unregister();<br>   };<br>  return (<br>   &lt;div&gt;<br>     &lt;h1&gt;Your App&lt;/h1&gt;<br>     &lt;button onClick={handleUnregister}&gt;Unregister Service Worker&lt;/button&gt;<br>   &lt;/div&gt;<br>   );<br>  }<br>export default App;</pre><h3>Import the registration in index file</h3><p>In your <strong>index.js</strong> file, import the this file as such:</p><pre>import * as serviceWorkerRegistration from &#39;./serviceWorkerRegistration&#39;;</pre><p>and register it at the very end</p><pre>serviceWorkerRegistration.register();</pre><h3>Dropdown Component</h3><p>Now, let’s develop a component that will send the actions we are listening to in service worker.</p><p>Create a components folder in src and create a file named recipeDropdown.jsx</p><p>Create states for recipes list, selected recipe, recipe details and error.</p><pre>const [recipes, setRecipes] = useState([]);<br>const [selectedRecipe, setSelectedRecipe] = useState(&#39;&#39;);<br>const [recipeDetails, setRecipeDetails] = useState(null);<br>const [error, setError] = useState(null);</pre><p>We have to fetch the recipes list to show in the dropdown. We will do that in useEffect and send the post message with action FETCH_RECIPES_LIST. The response will be handled by an event listener <strong>handleServiceWorkerMessage.</strong></p><pre>useEffect(() =&gt; {<br>  const fetchRecipesFromServiceWorker = () =&gt; {<br>      const handleMessage = (event) =&gt; handleServiceWorkerMessage(event);<br>      if (&#39;serviceWorker&#39; in navigator) {<br>          navigator.serviceWorker.addEventListener(&#39;message&#39;, handleMessage);<br><br>          // Wait for the service worker to be ready before sending a message<br>          navigator.serviceWorker.ready.then(() =&gt; {<br>              navigator.serviceWorker.controller?.postMessage({ type: &#39;FETCH_RECIPES_LIST&#39; });<br>          });<br>      } else {<br>          console.error(&#39;Service worker not supported&#39;);<br>          setError(&#39;Service worker not supported&#39;);<br>          fetchRecipesFromNetwork(); // Fallback if no service worker support<br>      }<br><br>      // Cleanup<br>      return () =&gt; {<br>          navigator.serviceWorker.removeEventListener(&#39;message&#39;, handleMessage);<br>      };<br>  };<br>  fetchRecipesFromServiceWorker();<br>}, []);</pre><p><strong>Note</strong>: It is important to clean up the event listeners to avoid memory leaks and prevent duplicate listeners.</p><p><strong>navigator.serviceWorker.ready</strong>: This ensures that the code only tries to interact with the service worker after it&#39;s fully ready and controlling the page. This can help avoid timing issues on initial load, <strong>especially in incognito mode where caching behaviour can differ.</strong></p><p>Create a method to handle when user selects a recipe. This will send the action FETCH_RECIPE_DETAILS and the response will also be handled by the same event listener handleServiceWorkerMessage. Remember to clean it up as well.</p><pre> /* <br>  * Handles recipe selection change<br>  * Requests details from the service worker<br>  */<br>  const handleRecipeChange = (e) =&gt; {<br>    const recipeId = e.target.value;<br>    setSelectedRecipe(recipeId);<br>    setError(null);<br>    const handleMessage = (event) =&gt; handleServiceWorkerMessage(event, recipeId);<br>    if (&#39;serviceWorker&#39; in navigator) {<br>        navigator.serviceWorker.ready.then(() =&gt; {<br>            navigator.serviceWorker.controller?.postMessage({<br>                type: &#39;FETCH_RECIPE_DETAILS&#39;,<br>                recipeId<br>            });<br>        });<br><br>        navigator.serviceWorker.addEventListener(&#39;message&#39;, handleMessage);<br>    }<br>    // Cleanup<br>    return () =&gt; {<br>        navigator.serviceWorker.removeEventListener(&#39;message&#39;, handleMessage);<br>    };<br>  };</pre><p>Let’s define the event listener method and a fallback method in case the service worker is not ready/supported and we need to fetch data from API.</p><p><strong>Note</strong>: Browsers in incognito mode restrict certain caching and service worker behaviours, the fallback method ensures that even if the service worker isn’t ready, the app can still fetch data.</p><pre>const handleServiceWorkerMessage = (event, recipeId = &#39;&#39;) =&gt; {<br>  const { type, data, error } = event.data;<br>  if (error) {<br>      setError(error);<br>  } else if (type === &#39;RECIPES_LIST&#39;) {<br>      setRecipes(data.recipes);<br>  } else if (type === &#39;RECIPE_DETAILS&#39; &amp;&amp; data.id == recipeId) {<br>      setRecipeDetails(data);<br>  }<br>};<br><br>/*<br>* Fallback in case service worker is not ready<br>*/<br>const fetchRecipesFromNetwork = async () =&gt; {<br>  try {<br>    const response = await fetch(&#39;https://dummyjson.com/recipes?select=name&#39;);<br>    const data = await response.json();<br>    setRecipes(data.recipes);<br>  } catch (error) {<br>    console.error(&#39;Network fetch error:&#39;, error);<br>    setError(&#39;Failed to fetch recipes from network.&#39;);<br>  }<br>};</pre><p>The main logic is done. Now, let’s write the HTML/CSS so we can interact with the dropdown and see if our cache is working.</p><h3>HTML/CSS</h3><p>In the above component, add the following HTML:</p><pre>return (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;div className=&quot;header&quot;&gt;<br>      &lt;h1&gt;Recipe Selector&lt;/h1&gt;<br>      {error &amp;&amp; &lt;div style={{ color: &#39;red&#39; }}&gt;{error}&lt;/div&gt;}<br>      &lt;select onChange={handleRecipeChange} value={selectedRecipe}&gt;<br>          &lt;option value=&quot;&quot; disabled&gt;Select a recipe&lt;/option&gt;<br>          {recipes.map((recipe) =&gt; (<br>              &lt;option key={recipe.id} value={recipe.id}&gt;<br>                  {recipe.name}<br>              &lt;/option&gt;<br>          ))}<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br>  <br>    {recipeDetails &amp;&amp; (<br>      &lt;div className=&quot;recipe-card&quot;&gt;<br>        &lt;div className=&quot;first-block&quot;&gt;<br>            &lt;div&gt;<br>              &lt;img src={recipeDetails.image} /&gt;<br>              &lt;h2&gt;{recipeDetails.name}&lt;/h2&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;p&gt;&lt;strong&gt;Cuisine:&lt;/strong&gt;  {recipeDetails.cuisine}&lt;/p&gt;<br>              &lt;p&gt;&lt;strong&gt;Cooking Time in minutes:&lt;/strong&gt;  {recipeDetails.cookTimeMinutes}&lt;/p&gt;<br>              &lt;p&gt;&lt;strong&gt;Prep time in minutes:&lt;/strong&gt;  {recipeDetails.prepTimeMinutes}&lt;/p&gt;<br>              &lt;p&gt;&lt;strong&gt;Servings:&lt;/strong&gt;  {recipeDetails.servings}&lt;/p&gt;<br>              &lt;p&gt;&lt;strong&gt;Calories per serving:&lt;/strong&gt; {recipeDetails.caloriesPerServing}&lt;/p&gt;<br>              &lt;p&gt;&lt;strong&gt;Difficulty:&lt;/strong&gt; {recipeDetails.difficulty}&lt;/p&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;p&gt;&lt;strong&gt;Ingredients:&lt;/strong&gt;&lt;/p&gt;<br>        &lt;ul&gt;<br>            {recipeDetails.ingredients.map((ingredient, index) =&gt; (<br>                &lt;li key={index}&gt;{ingredient}&lt;/li&gt;<br>            ))}<br>        &lt;/ul&gt;<br>        &lt;p&gt;&lt;strong&gt;Instructions:&lt;/strong&gt;&lt;/p&gt;<br>        &lt;ul&gt;<br>            {recipeDetails.instructions.map((instruction, index) =&gt; (<br>                &lt;li key={index}&gt;{instruction}&lt;/li&gt;<br>            ))}<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    )}<br>  &lt;/div&gt;<br>  );<br>}</pre><p><strong>Basic CSS to go with this (you can write this in App.css)</strong></p><pre>body{<br>  background-color: white;<br>  color: #c25251;<br>  padding: 20px 40px;<br>}<br>.container{<br>  max-width: 900px;<br>  margin: auto;<br>}<br>.header{<br>  text-align: center;<br>}<br>.header select{<br>  padding: 10px;<br>  border: none;<br>  border-bottom: 1px solid #c25251;<br>  color: #c25251;<br>}<br>.recipe-card{<br>  margin-top: 50px;<br>  border: 1px solid;<br>  border-radius: 20px;<br>  padding: 30px;<br>}<br><br>.recipe-card img{<br>  max-width: 300px;<br>  border-radius: 20px;<br><br>}<br><br>.first-block{<br>  display: flex;<br>  align-items: center;<br>  justify-content: space-between;<br>}</pre><p>Import the component in App.js</p><pre>import RecipeDropdown from &#39;./components/recipeDropdown&#39;;<br>import &#39;./App.css&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;RecipeDropdown /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Finally, run the application and let’s test the service worker!</p><pre>npm start</pre><p>To verify that caching is working:</p><ol><li>Open your app on <a href="http://localhost:3000/">http://localhost:3000/</a></li><li>Open DevTools (F12) in your browser.</li><li>Go to the <strong>Application</strong> tab, then <strong>Service Workers</strong> to ensure your service worker is active.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6sUrkMJlWjGYB0i5OHAnBw.png" /></figure><p>Select a few recipes from the dropdown, then head on over to the <strong>Cache Storage</strong> section under the <strong>Application</strong> tab and inspect the recipes-cache cache to see if the requests are being cached.</p><p>For first selection of a recipe, it should make a network call. Once the data is stored in cache, it should not make a network call but rather fetch from cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8hNS4XTSyng1DnOYN95-g.png" /></figure><p>Make sure to test with <strong>cache disabled</strong> in the <strong>Network</strong> tab of your browser for a true cache-first strategy. You can also test by clearing site data manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjW54sggqn9ACUF3u9-sgw.png" /></figure><p>If you run into any problems, check to see if cache is being stored and what network calls are being made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlqW67-a4KIyDP5EP3mBlA.png" /></figure><p>For example, data with ids 1,2 and 3 are already in cache. If we select those from dropdown, only a network call for their images should be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*mb5IHev1rc-t5BPii_NhFw.png" /></figure><p>You can also save these images in the cache for a more optimal performance.</p><p>So there you go, a very basic starting point for working with cache and service workers.</p><p>Let me know if you run into any problems. I’ll be happy to help :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7db2a4f5549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes concepts for beginners]]></title>
            <link>https://medium.com/@offbeatgs/kubernetes-concepts-for-beginners-f486f53c6a35?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f486f53c6a35</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 09:37:04 GMT</pubDate>
            <atom:updated>2024-04-08T09:37:04.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes is a container orchestration platform for scheduling and automating the deployment, management, and scaling of containerised application. <strong>It is an open source container orchestration tool/framework.</strong> Helps you manage application that are in hundreds or thousands of containers in different environments like physical, virtual or even hybrid environments. It provides high availability, scalability and disaster recovery.</p><p>Kubernetes schedules and automates container-related tasks throughout the application lifecycle, including:</p><ul><li><strong>Deployment</strong>: Deploy a specified number of containers to a specified host and keep them running in a desired state.</li><li><strong>Rollouts</strong>: A rollout is a change to a deployment. Kubernetes lets you initiate, pause, resume, or roll back rollouts.</li><li><strong>Service discovery</strong>: Kubernetes can automatically expose a container to the internet or to other containers using a DNS name or IP address.</li><li><strong>Storage provisioning</strong>: Set Kubernetes to mount persistent local or cloud storage for your containers as needed.</li><li><strong>Load balancing</strong>: Based on CPU utilisation or custom metrics, Kubernetes load balancing can distribute the workload across the network to maintain performance and stability.</li><li><strong>Autoscaling</strong>: When traffic spikes, Kubernetes autoscaling can spin up new clusters as needed to handle the additional workload.</li><li><strong>Self-healing for high availability</strong>: When a container fails, Kubernetes can restart or replace it automatically to prevent downtime. It can also take down containers that don’t meet your health-check requirements.</li></ul><p>One drawback of Kubernetes is that it is very complex and cost heavy. Though if we offload the master node/ control panel to a managed Kubernetes service like Amazon EKS, we can run a cluster without worrying about the underlying infrastructure.</p><h3>Basic architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kt6t6Q10fDZ3CIAIoX6JqQ.png" /></figure><p>It has at least one master node and a bunch of worker nodes. Each worker node has:</p><ol><li>A <strong>Kubelet</strong> that allows communication between worker nodes and master node. It ensures that the desired state is always maintained and receives instructions about which pods to run from the master node. You can have a number of docker containers running on the nodes.</li><li><strong>Container runtime</strong> which is in charge of pulling the container images from the registry, starting and stopping containers and managing its resources.</li><li><strong>Kube-proxy</strong> which is a networking proxy which is responsible for routining traffic to correct pods. Also provides load balancing by ensuring traffic is distributed evenly across the pods.</li></ol><p>Master server runs the following processes:</p><ol><li><strong>The API server </strong>which is the entry point to the cluster. The UI or API will talk to the API server with requests in yaml or json format.</li><li><strong>The controller manager</strong> which keep track of what’s happening in the cluster i.e if some container died or something needs to be repaired.</li><li><strong>Scheduler</strong> which is responsible for scheduling containers on different nodes based on workload and resources.</li><li><strong>etcd</strong> which is actually a storage that holds the current state of the cluster, has all the configuration data. Through this you can take backup and restore.</li></ol><p>*You should have a backup of the master node or at least two master nodes in the cluster so if one master node is down, the whole cluster does not shut down.</p><p>Between these worker nodes and master, there is a virtual network. It unites all the worker nodes to create one unified powerful machine that has the sum of all the resources of the individual nodes.</p><h3>Components of Kubernetes</h3><p><strong>Pod</strong> is the smallest unit that user can configure and interact with. It is a wrapper of the container. A worker node has multiple pods and pods have multiple containers inside. Usually you need one pod per application. So a DB will be one pod, a message broker will be another pod, a server will be another. The virtual network assigns each pod an internal IP address. Pods can be seen as an abstraction layer over the containers and we interact only with that. It handles everything about the container without our intervention. If a container dies inside a pod, it will handle that automatically.</p><p><em>However</em> pods are ephemeral, meaning they can die frequently and whenever they are restarted, they get a new IP address. Kubernetes offers <strong>Service</strong> that can sit in front of pods instead of dynamic IP addresses. It has a permanent IP address and a load balancer. The lifecycle of service and pod is not connected. To access an application, you would need and external service. Some services like database need to be internal though. The types of services are specified when creating one.</p><p>The IP that services provides is insecure, has the node’s IP and port. So the request first goes to<strong> Ingress </strong>which does the forwarding and converts it to a secure protocol. It routes traffic into the cluster.</p><p><strong>ConfigMap</strong> is a component that holds the urls of the applications. Usually you would write the url in an application but it is tedious work if the url changed because then you would have to rebuild the application. In this case, all the external configurations are stored in one place and pods can get the url from it. It is for non-confidential purpose only.</p><p>For confidential information like database username and password, Kubernetes has <strong>Secret</strong>. It stores the data in base 64 and for encryption, we need to use third party tools from cloud providers. You can use the data from configMap and secret in your pod as env or properties file.</p><p><strong>Volumes</strong> allows for data to persist in the pod even if it restarts by attaching a physical storage which could be on the local machine or remote (outside the cluster) like cloud storage. Kubernetes itself does not persist data, we need to manage it through volumes.</p><p>If one pod is down because we built a new container image, we would have downtime if a user tries to access the URL. To solve this, we replicate our nodes which have the same service. To replicate, we create a blueprint in <strong>Deployment</strong> and specify the number of replicas we want. Deployment is an abstraction layer over pods.</p><p>We cannot replicate databases though because it has a state to maintain. It should be done through <strong>StatefulSet</strong> instead of deployment. It will take care or replicating the pods and scaling them down or up and making sure read and writes are synchronised so there are no inconsistencies. However this can be a bit challenging and common practice is to host stateless applications in kubernetes and to host DB outside of the cluster.</p><h3>Configuration File</h3><ol><li>Metadata like name</li><li>Specification, what we are creating e.g service, deployment and their specific attributes</li><li>Status, it is managed by kubernetes. Compares if the desired state is equal to actual state. etcd provides this status information.</li></ol><p><strong><em>Reference</em></strong>: <a href="https://www.youtube.com/watch?v=aSrqRSk43lY">Kubernetes Explained</a> (This IBM video provides excellent visual explanation)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f486f53c6a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github action for lint]]></title>
            <link>https://medium.com/@offbeatgs/github-action-for-lint-127f28fbc739?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/127f28fbc739</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 07:26:00 GMT</pubDate>
            <atom:updated>2024-04-08T05:29:45.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3eu1JI68wYn5iFLERKWHg.png" /></figure><p>GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline. You can create workflows that build and test every pull request to your repository or deploy merged pull requests to production.</p><p>Some terminologies to be familiar with are mentioned below:</p><p>A <strong>workflow</strong> is a configurable automated process that will run one or more jobs. Workflows are defined by a YAML file checked in the .github/workflows directory in a repository.</p><p>An <strong>event </strong>is a specific activity in a repository that triggers a workflow run. For example, activity can originate from GitHub when someone creates a pull request, opens an issue, or pushes a commit to a repository.</p><p>An <strong>action </strong>is a custom application for the GitHub Actions platform that performs a complex but frequently repeated task.</p><p><strong>Prerequisites:</strong></p><p><em>ESlint or any other linter should be configured in the project</em></p><p>Linting is the automated checking of your source code for programmatic and stylistic errors. To trigger the checking of code against eslint rules on the project whenever a pull request is created, we need to add the following code in the YAML file in .github/workflows/eslint.yml:</p><pre>name: ESLint check <br> <br>on: <br> pull_request: <br> types: [opened, synchronize] <br> branches: <br> - branchname<br> <br>jobs: <br> eslint: <br> runs-on: ubuntu-latest <br> steps: <br> - name: Checkout code <br> uses: actions/checkout@v2 <br> with: <br> ref: ${{ github.event.pull_request.head.sha }} <br> <br> - name: Setup Node.js <br> uses: actions/setup-node@v2 <br> with: <br> node-version: &#39;16.14.2&#39; <br> <br> - name: Restore cached dependencies <br> id: cache-restore <br> uses: actions/cache@v3 <br> with: <br> path: ./src/node_modules <br> key: npm-${{ hashFiles(&#39;./src/package-lock.json&#39;) }} <br> <br> - name: Install dependencies <br> if: steps.cache-restore.outputs.cache-hit != &#39;true&#39; <br> run: | <br> cd src <br> npm ci - ignore-scripts <br> <br> - name: Lint <br> run: | <br> cd src <br> npm run lint</pre><p>We have defined the workflow name as <strong>ESLint check</strong>. Every time there is a pull request against the mentioned branch, This GitHub action will:</p><ol><li>Check out the committed code due to ‘<strong>ref</strong>’</li><li>Set up node with v.16.14.2 (or any other version compatable with your project)</li><li>Restore the dependencies from cache with a key that uses package-lock.json hash file as name. This is done to skip installing dependencies at every run and only install it when there is a change in package-lock file.</li><li>If the cache did not exist or package.lock was updated, it will install dependencies using npm ci.</li><li>Run ‘<strong>npm run lint</strong>’ on the entire project to report any linting errors or warnings.</li></ol><p><strong>Details:</strong></p><ul><li><strong>types: [opened, synchronize]</strong></li></ul><p>‘types’ parameter specifies the types of pull request on which the pipeline should be triggered. Option <strong>‘opened’ </strong>will trigger the pipeline when the new pull request is created. Option <strong>‘synchronize</strong>’ will trigger pipeline when new commit is added to the pull request</p><ul><li><strong>ref: ${{ github.event.pull_request.head.sha }}</strong></li></ul><p>By using ‘github.event.pull_request.head.sha’, GitHub will checkout to the most recent commit on the head branch of the pull request.</p><ul><li><strong>key: npm-${{ hashFiles(‘./src/package-lock.json’) }}</strong></li></ul><p>This creates a cache key. ‘hashFiles’ generates SHA256 hash of ‘package-lock.json ‘ file in the repository. We create this key to ensure that if the package-lock.json file is changed, a new cache will be created.</p><ul><li><strong>if: steps.cache-restore.outputs.cache-hit != ‘true’</strong></li></ul><p>This IF condition checks if the step with id ‘cache-restore’ was successful in finding the cache or not. If successful, it will skip npm ci step otherwise execute it.</p><p><strong><em>Hope this helps!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127f28fbc739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from TSlint to ESlint in Angular]]></title>
            <link>https://medium.com/@offbeatgs/migrating-from-tslint-to-eslint-in-angular-624ab92522c8?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/624ab92522c8</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[tslint]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 07:00:23 GMT</pubDate>
            <atom:updated>2024-04-04T07:00:23.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTC-BKqUiRp2BhK2VflsvQ.png" /></figure><p>Tslint was the go-to linter in the past but it is deprecated now and it is recommended to use ESlint. For some legacy projects that have been in production since the last 6–7 years, it might be a hassle to convert the linter. Following are the steps you can take to migrate it efficiently:</p><h3>Pre-requisite:</h3><p>Make sure that Node version that you are using with web client is compatible. For my project, I was using <strong>12.22.0.</strong></p><h3>Setup:</h3><ul><li>Install eslint using the following command:</li></ul><pre>npm install - save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin</pre><p>The command above adds ESLint, adds a parser that makes ESLint understand TypeScript, and adds some TypeScript-specific rules.</p><ul><li>Update tslint from 5.11 to 5.18</li></ul><pre>npm i tslint@v5.18</pre><p>This is required as the following command requires tslint to be at least 5.18.</p><ul><li>Run the following command to convert tslint files to eslint</li></ul><pre>npx tslint-to-eslint-config</pre><p>Now, to make the actual migration simpler, run the <a href="https://github.com/typescript-eslint/tslint-to-eslint-config">tslint-to-eslint-config</a> utility. This tool will take your TSLint configuration and create the <em>closest</em> ESlint configuration from it. There should now be a new .eslintrc.js file and a log file (tslint-to-eslint-config.log).</p><ul><li>Run the following commands to install additional packages required:</li></ul><pre>npm install eslint-plugin-import@latest - save-dev<br>npm install @angular-eslint/eslint-plugin@latest - save-dev<br>npm install @typescript-eslint/eslint-plugin-tslint@latest - save-dev</pre><ul><li>Update the scripts in package.json to the following:</li></ul><pre>&quot;lint&quot;: &quot;eslint -c .eslintrc.js - ext .ts ./&quot;,</pre><p>Update the .eslintrc.js file, change:</p><pre>&quot;@typescript-eslint/indent&quot;: &quot;error&quot;,</pre><p>to</p><pre>&quot;@typescript-eslint/indent&quot;: [<br>            &quot;error&quot;,<br>            2,<br>            {<br>                &quot;SwitchCase&quot;: 1<br>            }<br>        ],</pre><p>Changing this will set default tab spaces to <strong><em>2</em></strong> instead of default <strong><em>4</em></strong><em>.</em></p><h3>Execution:</h3><ul><li>Now run the following command and everything should run smoothly</li></ul><pre>npm run lint</pre><p><strong>Reference</strong>: <a href="https://code.visualstudio.com/api/advanced-topics/tslint-eslint-migration">https://code.visualstudio.com/api/advanced-topics/tslint-eslint-migration</a></p><h3>Add and run EsLint autofix:</h3><p>In order for eslint to automatically fix formatting errors, add a handy script which can be used in future. Update package.json, add</p><pre>&quot;fix-lint&quot;: &quot;eslint - fix -c .eslintrc.js - ext .ts ./&quot;,</pre><p>below</p><pre>&quot;lint&quot;: &quot;eslint -c .eslintrc.js - ext .ts ./&quot;,</pre><p>After that, when you run the command:</p><pre>npm run fix-lint</pre><p>this will automatically fix most of the formatting issues.</p><p><strong>NOTE: </strong>autofix will not resolve all of the issues pointed out by eslint. Some issues will still require fixing manually.</p><p>You can now remove the tslint.json and uninstall the tslint package.</p><pre>npm uninstall tslint</pre><p><strong><em>Hope this helps!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=624ab92522c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical guide to memory leaks in Angular and how to solve them]]></title>
            <link>https://blog.stackademic.com/a-practical-guide-to-memory-leaks-in-angular-and-how-to-solve-them-16c91e69437b?source=rss-24b7dabc37d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/16c91e69437b</guid>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[chrome-dev-tools]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[best-coding-standards]]></category>
            <dc:creator><![CDATA[Kanwal Shariq]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 07:53:14 GMT</pubDate>
            <atom:updated>2024-09-24T12:12:19.460Z</atom:updated>
            <content:encoded><![CDATA[<p>A memory leak is caused when a memory allocation is not cleared when it is not needed. You can think of it as a large number of state or variables that are still holding data even when they are not being used. It is not a bug that most functional tests could catch as the functionality would be running fine. This leak can be caught by CPU Usage in chrome dev tools or your system monitor.</p><p>I ran into this problem recently and spent days figuring it out through chrome dev tools. Here, I will tell you of one of the simple ways to catch them, fix them and notice the change.</p><p>Before jumping into dev tools, let’s see some of the most common mistakes that lead to memory leakage. To find the source of it, you can clear out the code in the file that is causing the leak, then put it back one by one to see what is causing the issue.</p><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3><strong>1. Not unsubscribing to observables.</strong></h3><p>Example of a wrong observable:</p><pre>this.loadingData$ = this.store.pipe(select(getDataIsLoading)).subscribe();</pre><p>Correct Usage:</p><pre>this.loadingData$ = this.store.pipe(select(getDataIsLoading), takeUntil(this.ngUnsubscribe$)).subscribe();</pre><p>This is one of the most common mistake developers make while using RxJs. You should make sure that if you are using an observable, you should either unsubscribe to it or use it one time if that matches your use-case. Take(1) is a very important concept. I dealt with a memory leak that was 70% the fault of using takeUntil() where it should have been take(1).</p><p>Example for take(1):</p><pre>this.store.pipe(select(getData), take(1)).subscribe((data) =&gt; {<br>      this.data = data;<br>});</pre><p>Example for takeUntil():</p><pre>this.store.pipe(select(getData), takeUntil(this.ngUnsubscribe$)).subscribe(() =&gt; {<br>      this.newData(true);<br>});</pre><p>And this ngUnsubscribe would be completed in ngOnDestroy.</p><pre>ngOnDestroy() {<br>    this.ngUnsubscribe$.next();<br>    this.ngUnsubscribe$.complete();<br> }</pre><p>If like me, you are working on a component that constantly fetches new data, is not destroyed and has components, it is likely you have observables which are being initiated within the takeUntil() of another observable.</p><p>Say you have a observable listening for data, as soon as it arrives you want to compute something based on another observable, in that case, the inner observable should be destroyed first and then recreated like</p><pre>this.dataChangedUnsubscribe$.next(true);<br>this.dataChangedUnsubscribe$.complete();<br>this.dataChangedUnsubscribe$ = new Subject&lt;boolean&gt;();</pre><h3><strong>2. Creating a large number of objects or closures that are not properly cleaned up.</strong></h3><p>Within an observable, make sure to clean up objects and variables and on ngOnDestroy as well. This helps in cleaning up the detached DOM elements. Keeping large amounts of data in memory for extended periods of time also results in memory leakage.</p><h3><strong>3. Registering event listeners or timers that are not properly removed.</strong></h3><p>Another thing that is often overlooked is clearing timeouts.</p><pre>@HostListener(&#39;paste&#39;, [&#39;$event&#39;]) blockPaste(event: KeyboardEvent) { <br>    setTimeout(() =&gt; {<br>        this.value = event.srcElement[&#39;value&#39;];<br>        event.preventDefault();<br>     }, 120);<br>  }</pre><p>In Angular, you typically do not need to manually unsubscribe from @HostListener event handlers to prevent memory leaks. Angular manages the lifecycle of these event listeners for you, but if you have a complex flow of code and or if you’re manually adding listeners to the DOM, it is good practice to clean up the listeners.</p><p>This could be changed to:</p><pre>@HostListener(&#39;paste&#39;, [&#39;$event&#39;]) blockPaste(event: KeyboardEvent) {<br>    this.blockPasteListener = setTimeout(() =&gt; {<br>      this.value = event.srcElement[&#39;value&#39;];<br>      event.preventDefault();<br>    }, 120);<br>  }</pre><p>And the ngOndestroy should look something like this:</p><pre>ngOnDestroy() {<br>    window.removeEventListener(&#39;scroll&#39;, this.scrollEvent,  true);<br>    clearTimeout(this.blockPasteListener);<br>    document.removeEventListener(&#39;paste&#39;, this.blockPaste);<br>  }<br>}</pre><p>Same goes for any mouse or keyboard listeners.</p><pre>this.renderer.listen(div, &#39;mousedown&#39;, (e) =&gt; {...}</pre><p>This should be changed to:</p><pre>private mouseDownListener: () =&gt; void;<br>//rest of the code <br>this.mouseDownListener = this.renderer.listen(div, &#39;mousedown&#39;, (e) =&gt; {...}<br>//rest of the code<br>ngOnDestroy() {<br>    this.ngUnsubscribe$.next(true);<br>    this.ngUnsubscribe$.complete();<br>    document.removeEventListener(&#39;mousemove&#39;, this.onMouseMove); //if used<br>    this.mouseDownListener();<br>  }</pre><p>These were some of the common mistakes in the code that result in memory leaks. Lets take a look at chrome dev tools now.</p><h3><strong>Catching and verifying memory leaks through chrome dev tools:</strong></h3><ol><li>On chrome, right click on the screen and open the inspector</li><li>Go to more options -&gt; more tools</li><li>Select performance monitor</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYTAiC10lX-JppitCXks-A.png" /><figcaption>Performance monitor</figcaption></figure><p>The performance monitor will show a graph displaying any jumps in the memory, CPU Usage, JS heap size etc. Take note of the graph and numbers than go to the component where you think the leak is. Change components or if you have a list of items, click on different items and observe if the graph shows a large difference. If the heap size is large and not reducing once you go back to the starting point, AND not reducing when you click on the garbage collector as shown below, you have a memory leak.</p><p>*C<em>hrome has a garbage collector that runs after every few minutes. You can run it manually from here. If the memory size is significantly larger than before even after running the garbage collector, than there is a leak.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HDXB8CeIBX7aKdEhcabOg.png" /></figure><p>You can also figure out which objects are being retained through heap snapshots. In the memory tab, take a heap snapshot before clicking on the component that is causing trouble.</p><p>Then take another heap snapshot after clicking on the component. Then click on comparison and compare the two snap shots to see which new objects are added.</p><p>You can then take another heap snapshot after going back to the starting point to see which objects are being retained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXTR4VCdFKgQjbO0wrzpag.png" /></figure><h3><strong>That’s it!</strong></h3><p>The best practice for fixing these leaks, especially if you’re a beginner, is to go over the code one by one and see which line of code is causing the issue. That way your Angular concepts would be put to use and you can verify if the leak is fixed through the dev tools.</p><p>Thank you for reading and good luck! Memory leaks are tedious to resolve but once you do fix them, it feels like you climbed Mount Everest. If there’s anything you don’t understand or want further help with, please comment below. I’ll be more than happy to help!</p><blockquote><em>👉 </em><strong>Also learn about these 7 lesser-known Angular features to boost your App’s performance:</strong></blockquote><p><a href="https://differ.blog/p/unlocking-angular-7-hidden-features-for-developers-72487d">Angular Hidden Features for Developers</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c91e69437b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/a-practical-guide-to-memory-leaks-in-angular-and-how-to-solve-them-16c91e69437b">A practical guide to memory leaks in Angular and how to solve them</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>