<?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 Eyuel Berga Woldemichael on Medium]]></title>
        <description><![CDATA[Stories by Eyuel Berga Woldemichael on Medium]]></description>
        <link>https://medium.com/@eyuelberga?source=rss-4106ccb20b99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F2d-dBWX5azLSPUewh5ODw.png</url>
            <title>Stories by Eyuel Berga Woldemichael on Medium</title>
            <link>https://medium.com/@eyuelberga?source=rss-4106ccb20b99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:52:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eyuelberga/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[Exploring Wildcards in Java: Making Generic Methods More Flexible]]></title>
            <link>https://medium.com/geekculture/exploring-wildcards-in-java-making-generic-methods-more-flexible-eac3180dbb1c?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac3180dbb1c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 01:51:42 GMT</pubDate>
            <atom:updated>2023-06-03T01:51:42.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xl_5vpyTwhi2QyD2" /><figcaption>Photo by <a href="https://unsplash.com/fr/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Generic methods in Java provide a powerful way to create reusable code that can work with different data types. They allow you to write methods that can handle a variety of data types while maintaining type safety. However, there are situations where you may need even more flexibility in handling different types within your generic methods. This is where wildcard type constraints come into play.</p><p>In this article, we will be discussing the use of wildcards to increase the flexibility of your generic methods in Java. We will delve into the concept of wildcard types, their significance, and the effective ways to utilize them in your programming. By the end of this article, you will have a comprehensive understanding of how wildcards can enhance the versatility of your generic methods.</p><h3>What are Generic Methods?</h3><p>Generic methods allow us to write code that is not tied to a specific data type. They have type parameters that allow the method to accept arguments of different types while providing type safety.</p><p>The syntax for declaring a generic method is as follows:</p><pre>public &lt;T&gt; returnType methodName(T parameter) {<br>    // Method implementation<br>}</pre><p>Here, &lt;T&gt; denotes the type parameter, which can be any valid identifier. The type parameter is enclosed in angle brackets (&lt;&gt;).</p><p>Generic methods enhance our code by introducing more flexibility and reusability. They also provide compile-time type safety by ensuring that the types passed to the method are compatible with the declared type parameters. Which helps catch type-related errors early during compilation.</p><p>To better understand the power of generic methods, let&#39;s take a simple swap method that swaps two elements in an array:</p><pre>public static void swap(int[] array, int i, int j) {<br>    int temp = array[i];<br>    array[i] = array[j];<br>    array[j] = temp;<br>}</pre><p>The above implementation only works for int data types. If we need to use swap for another data type, we need to write another method. But instead of writing separate swap methods for different types, we can create a single generic method swap that can handle any type :</p><pre>public static &lt;T&gt; void swap(T[] array, T i, T j) {<br>    T temp = array[i];<br>    array[i] = array[j];<br>    array[j] = temp;<br>}</pre><h3>More Flexibility with Wildcards</h3><p>With wildcard type constraints, we can define an uncertain or restricted set of types in our generic methods. This enables us to write more flexible generic methods that can handle a variety of types, such as unknown or particular subtypes. They are denoted by the wildcard character ?.</p><p>There are three types of wildcard constraints: upper bound, lower bound, and unbounded wildcards.</p><h4>Upper Bound Wildcards</h4><p>An upper bound wildcard is denoted by ? extends Type, where Type is the upper bound. It allows any type that is a subtype of the specified upper bound which can be a class or an interface. By using an upper bound wildcard, the method becomes capable of handling a variety of subtypes, which enhances its flexibility in dealing with different types.</p><p>Here’s a simple example that demonstrates the usage of an upper bound wildcard:</p><pre>public static double calculateAverage(List&lt;? extends Number&gt; numbers) {<br>    double sum = 0;<br>    for (Number number : numbers) {<br>        sum += number.doubleValue();<br>    }<br>    return sum / numbers.size();<br>}</pre><p>In this example, the calculateAverage method accepts a List parameter with an upper bound wildcard ? extends Number. It means that the method can work with a List of any type that extends Number. The method can handle a variety of input types such as lists of integers, doubles, or any other subclass, providing flexibility in the input type.</p><h4>Lower Bound Wildcards</h4><p>A lower bound wildcard is denoted by ? super Type, where Type is the lower bound. It allows any type that is a supertype of the specified lower bound which can be a class or an interface. By using a lower bound wildcard, it becomes possible to accept a variety of supertypes with greater flexibility.</p><p>Here’s an example that demonstrates the usage of a lower bound wildcard:</p><pre>public static &lt;T&gt; int countOccurrences(List&lt;? super T&gt; list, T targetElement) {<br>    int count = 0;<br>    for (Object element : list) {<br>        if (element.equals(targetElement)) {<br>            count++;<br>        }<br>    }<br>    return count;<br>}</pre><p>In this example, we have a generic method countOccurrences that takes a List parameter with a lower bound wildcard type ? super T. The method also takes a targetElement of type T, which represents the element we want to count the occurrences of.</p><p>This method counts the number of occurrences of the targetElement in the list. By using the lower bound wildcard, the method can work with a List of any type that is a superclass of T, enabling flexibility in handling different related types.</p><h4>Unbounded Wildcards</h4><p>An unbounded wildcard is denoted by a simple ?. It represents an unknown type and allows any type to be used. When writing code, unbounded wildcards come in handy if you want to make it independent of any particular type or if the operations you need to perform are applicable to all types.</p><p>Here is an example that showcases how to use an unbounded wildcard:</p><pre>public static void printList(List&lt;?&gt; list) {<br>    for (Object element : list) {<br>        System.out.println(element);<br>    }<br>}</pre><p>In this example, the printList method accepts a List parameter with an unbounded wildcard ?. It means that the method can work with a List of any type. Although we don&#39;t know the specific type, we can still iterate over the list and perform operations that are common to all types, such as printing the elements.</p><h3>Conclusion</h3><p>Wildcards in Java are a powerful feature that allows us to make our generic methods more flexible and adaptable. By using upper bound, lower bound, or unbounded wildcards, we can handle unknown types, ensure type safety, and accept a range of related types. Understanding and applying wildcard type constraints in your Java code will enable you to write more versatile and robust generic methods.</p><p>I hope this article has provided you with a comprehensive understanding of wildcard constraints in Java to start using them in your code.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac3180dbb1c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/exploring-wildcards-in-java-making-generic-methods-more-flexible-eac3180dbb1c">Exploring Wildcards in Java: Making Generic Methods More Flexible</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Cloudflare Workers to Make a Link in Bio Tool]]></title>
            <link>https://eyuelberga.medium.com/how-to-use-cloudflare-workers-to-make-a-link-in-bio-tool-c4c5e1be5238?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4c5e1be5238</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Fri, 05 May 2023 15:08:56 GMT</pubDate>
            <atom:updated>2023-05-05T15:08:56.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eyy71j76ACfYdjKV" /><figcaption>Photo by <a href="https://unsplash.com/es/@edge2edgemedia?utm_source=medium&amp;utm_medium=referral">Edge2Edge Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://workers.cloudflare.com/">Cloudflare Workers</a> provide a globally distributed serverless environment that is highly available and scalable. In this article, we will leverage the power of Cloudflare Workers and <a href="https://www.cloudflare.com/products/workers-kv/">KV</a>, a low latency distributed key-value store to build a simple Link in Bio tool, similar to <a href="https://linktr.ee/">Linktree</a> and <a href="https://lnk.bio/">Lnk.Bio</a>.</p><h3>A Sneak Preview</h3><p>This is what the finished project will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3W5YlurWuYf1gwsq" /><figcaption>There will be a form for creating a new page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FZiJAZ8bjeoZn3Tm" /><figcaption>After successfully submitting the form, the link to share on social media will be displayed.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G0OrZW8GAHctEnVE" /><figcaption>This is what people will see when they go to the link.</figcaption></figure><h3>Initializing a new Project</h3><p>Let’s start by initializing a new project using the <a href="https://developers.cloudflare.com/workers/wrangler/get-started/">Wrangler CLI</a>. Go ahead and run this command:</p><pre>$  npx wrangler init link-in-bio</pre><p>We will be using Typescript for this tutorial, so answer yes when prompted.</p><h3>Creating a KV Store</h3><p>Run the following commands to create a new KV store:</p><pre>$ npx wrangler kv:namespace create &quot;LINK_IN_BIO&quot;<br>$ npx wrangler kv:namespace create &quot;LINK_IN_BIO&quot; --previews</pre><p>We will also need to update the wrangler.toml file to include the namespace bindings.</p><pre>...<br>kv_namespaces = [{ binding = &quot;LINK_IN_BIO&quot;, id = &quot;xxxxxxxxx&quot;, preview_id = &quot;xxxxxxxxx&quot;}]</pre><h3>Running locally</h3><p>We will start up the dev server to build and run the project locally by running the following command:</p><pre>$ npx wrangler dev</pre><h3>Creating the web templates</h3><p>We need three pages for the project. The home page will have the form. The profile page will render the links and profile info of the user. Lastly, we will need a success page that will be rendered after the user successfully submitted the form. It will contain the link that will be shared on the social media profile.</p><p>The templates are standard HTML documents wrapped around a function. They are quite long to include here, so check them out on <a href="https://github.com/eyuelberga/LinkInBio/tree/main/src">Github</a>. There are also some TypeScript interfaces in <a href="https://github.com/eyuelberga/LinkInBio/blob/main/src/profile_page.ts">profile_page.ts</a>. The ProfileContent is the input type for the profile page template.</p><pre>export interface Link {<br>  name: string;<br>  url: string;<br>}<br>export interface ProfileContent {<br>  name: string;<br>  picture: string;<br>  description?: string;<br>  links: Link[];<br>}</pre><p>After creating those files, import them to index.js.</p><pre>import profilePage, { ProfileContent, Link } from &quot;./profile_page&quot;;<br>import homePage from &quot;./home_page&quot;;<br>import successPage from &quot;./success_page&quot;;</pre><p>We will also destructure the LINK_IN_BIO, which is our KV store, from the env object. Our fetch function now looks something like this:</p><pre>export default {<br>  async fetch(request: Request, { LINK_IN_BIO }: Record&lt;string, any&gt;): Promise&lt;Response&gt; {<br>     ...<br>  }<br>}</pre><h3>Handling HTTP Requests</h3><p>There are two GET requests we need to handle. If there is no path we’ll just render the homePage.</p><pre>// handle get request<br>if (request.method.toLowerCase() === &quot;get&quot;) {<br>   const url = new URL(request.url);<br>   // home page route<br>   if (url.pathname === &quot;/&quot;) {<br>      return new Response(homePage, { headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } });<br>    }<br>}</pre><p>If there is a path in the URL we will render the profilePage with the page content we get from our KV store. First, we extract the key from the URL and then get the value from KV by calling the get method on LINK_IN_BIO.</p><pre>// handle get request<br>if (request.method.toLowerCase() === &quot;get&quot;) {<br>   const url = new URL(request.url);<br>   // home page route<br>   if (url.pathname === &quot;/&quot;) {<br>      return new Response(homePage, { headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } });<br>    }<br>/**<br>     * Additional code to handle route with a path <br>     **/<br>    // extract key from url<br>    const key = url.pathname.replaceAll(&quot;/&quot;, &quot;&quot;);<br>    // render profile page<br>    const content = await LINK_IN_BIO.get(key);<br>    if (content) {<br>       return new Response(profilePage(JSON.parse(content)), { headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } });<br>     }<br>     // key is not in the store<br>     return new Response(&quot;Page does not exist&quot;, { status: 404 });<br>}<br></pre><p>The next thing we need to handle is the POST request. This is invoked when the form on the home page is submitted. The first thing to do is get the form data from the request. We will also create the variable namedcontent to store the profile content we will put in KV. It will have a type of ProfileContent, which is the same as the input for the profilePage template.</p><pre>// handle post request<br>if (request.method.toLowerCase() === &quot;post&quot;) {<br>   const formData = await request.formData();<br>   const content: ProfileContent = { name: &#39;&#39;, picture: &#39;&#39;, links: [] };<br>}</pre><p>We also need two helper functions.toBase64 will be used to convert the profile picture to a base64 string and generateId a simple unique ID generator for generating keys for our KV store.</p><pre>// convert file to base64<br>const toBase64 = async (file: File) =&gt; {<br>  const buffer = await file.arrayBuffer();<br>  var binary = &#39;&#39;;<br>  var bytes = new Uint8Array(buffer);<br>  var len = bytes.byteLength;<br>  for (var i = 0; i &lt; len; i++) {<br>    binary += String.fromCharCode(bytes[i]);<br>  }<br>  const base64 = btoa(binary);<br>  return `data:${file.type};base64,${base64}`<br>};<br><br>// generate unique id<br>const generateId = () =&gt; {<br>  return btoa((Date.now() * Math.random() + &quot;&quot;));<br>}</pre><p>The form on the home page allows users to add an infinite number of links to the form. Each new link input will have a number associated with it, like link_name_1 and link_url_1. You can take a look at the code on <a href="https://github.com/eyuelberga/LinkInBio/blob/main/src/home_page.ts">Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*lh0cpNl4lOTTtPk_" /></figure><p>We will write some code here to get all the link names and URLs from the form and group them based on their number. We map them in an object first and then store the list of links in the content variable.</p><pre>// handle post request<br>if (request.method.toLowerCase() === &quot;post&quot;) {<br>   ...<br>   // map to store all links in the form<br>   const linkMap: Record&lt;number, Link&gt; = {}<br>   // iterate over all entries in the form data <br>   for (const [key, value] of formData) {<br>      // extract number from the field name<br>      const numberMatch = key.match(/\d+/)<br>      const number = numberMatch ? parseInt(numberMatch[0]) : undefined;<br>      // add link name to linkMap<br>      if (key.includes(&quot;link_name&quot;)) {<br>         if (number &amp;&amp; typeof value === &quot;string&quot;)<br>            linkMap[number] = { ...linkMap[number], name: value }<br>      }<br>      // add link url to linkMap<br>      else if (key.includes(&quot;link_url&quot;)) {<br>         if (number &amp;&amp; typeof value === &quot;string&quot;)<br>             linkMap[number] = { ...linkMap[number], url: value }<br>       }<br>   }<br>   // add links to content from linkMap<br>   content.links = Object.values(linkMap);<br>}</pre><p>Next, we’ll get the name, description, and picture from the request and also add them to our content variable.</p><pre>// handle post request<br>if (request.method.toLowerCase() === &quot;post&quot;) {<br>   ...<br>   // map to store all links in the form<br>   const linkMap: Record&lt;number, Link&gt; = {}<br>   // iterate over all entries in the form data <br>   for (const [key, value] of formData) {<br>       ...<br>       // add name and description to content<br>       else if ((key === &quot;name&quot; || key === &quot;description&quot;) &amp;&amp; typeof value === &quot;string&quot;) {<br>          content[key] = value;<br>        }<br>        // add profile picture to content<br>        else if (key === &quot;picture&quot; &amp;&amp; typeof value !== &quot;string&quot;) {<br>           content[key] = await toBase64(value);<br>        }<br>   }<br>   ...<br>}</pre><p>Okay, the last thing we need to do now is add the content to our KV store and display the success page.</p><pre>// handle post request<br>if (request.method.toLowerCase() === &quot;post&quot;) {<br>   ...<br>   // generate a unique ID<br>   const id = generateId();<br>   // add content to KV<br>   await LINK_IN_BIO.put(id, JSON.stringify(content));<br>   // display success page<br>   return new Response(successPage(id), { headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } });<br>}</pre><h3>Publishing</h3><p>We’re all done with our implementation, so let’s deploy it. To publish our Cloudflare Worker we need to run the following command:</p><pre>$ npx wrangler publish</pre><p>Now our workers will be running across the globe. Awesome!</p><h3>Conclusion</h3><p>There are still some modifications we could do like adding authentication, custom IDs, and customizable profile templates. But I hope this tutorial gave you an idea of the kinds of applications you can build with Cloudflare Workers and KV.</p><p>I hope you enjoyed reading this article. You can find the source code for the project on <a href="https://github.com/eyuelberga/LinkInBio/">Github</a> and also check out the <a href="https://link-in-bio.eyuelberga.workers.dev/">live demo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c5e1be5238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Optimize Typeahead Search in Your Web Application]]></title>
            <link>https://medium.com/geekculture/how-to-optimize-typeahead-search-in-your-web-application-8246cac5b05f?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/8246cac5b05f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 20:32:42 GMT</pubDate>
            <atom:updated>2023-01-01T20:32:42.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V3Fh6A1_fcCmiahu" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You might have seen typeahead search in action on many websites and applications that have a search feature, such as online shopping sites, social media platforms, or search engines. It is a common feature that is designed to make it easier for users to find what they are looking for by providing them with relevant suggestions as they type their search query.</p><p>If you have a typeahead search on your website or are planning to add one, this article will show you how you can make your typeahead search less resource-intensive while not compromising on usability using a simple programming technique called debouncing.</p><h4>What is debouncing?</h4><p>Debouncing is a technique that is used to limit the frequency at which a function is called. It is often used in JavaScript when working with events that are triggered frequently, such as window resizes or input events, to prevent the function from being called too often and potentially causing performance issues.</p><p>Debouncing can be used to optimize typeahead search by limiting the frequency at which the search function is called. This can be especially useful if your search function is resource-intensive or if it makes an API call that is rate-limited.</p><h4>Typeahead search without debouncing</h4><p>First, let&#39;s take a look at a simple implementation of a typeahead search without debouncing:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftypeahead-search-without-debouncing-km6wbf%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fkm6wbf&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkm6wbf%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8036d9d8062e8e7ca0e83f7b85155378/href">https://medium.com/media/8036d9d8062e8e7ca0e83f7b85155378/href</a></iframe><p>With this implementation, we are making a network request every time a character is inserted into the input field. You can see from the console logs that we make a total of 11 API calls to search for “hello world”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Awcpt6ZL-8O3nNSYYGzZ6Q.png" /><figcaption>Searching for “hello world”</figcaption></figure><p>This typeahead search implementation is inefficient for a number of reasons:</p><ol><li><strong>Unnecessary API calls:</strong> If the search function is called every time the user types a keystroke, especially if the user types quickly, can lead to a large number of unnecessary API calls and potentially cause performance issues.</li><li><strong>Unnecessary DOM updates</strong>: If the search results are displayed and updated every time the search function is called, this will lead to a lot of unnecessary updates to the DOM, which also causes performance issues.</li><li><strong>Out-of-sync search results:</strong> If the search function is called too frequently, the search results may not always be in sync with the user’s input. For example, if the user types a long search query and the search function is called after each keystroke, the search results may be displayed and updated multiple times before the user finishes typing their query. This can be confusing for users and can make the search feature less user-friendly.</li></ol><h4>Debounce to the rescue!</h4><p>Using debouncing we can address these issues by limiting the frequency at which the search function is called and the search results are displayed and updated.</p><p>A standard implementation of a debounce function in Javascript looks something like this:</p><pre>function debounce(callback, delay) {<br>  let timeout;<br>  return function () {<br>    const context = this;<br>    const args = arguments;<br>    clearTimeout(timeout);<br>    timeout = setTimeout(function () {<br>      callback.apply(context, args);<br>    }, delay);<br>  };<br>}</pre><p>The debounce function takes two arguments: a callback function and a delay. It returns a new function that can be called to debounce the callback function.</p><p>The new function works by setting a timeout whenever it is called. If the timeout already exists, it is cleared and a new one is set. This means that if the new function is called multiple times within the delay period, only the last call will be executed.</p><p>When the delay period has passed, the timeout is executed by calling the callback function with the correct this value and the arguments that were passed to the new function. This ensures that the callback function is only called once per delay period, regardless of how many times the new function is called.</p><p>Now let&#39;s add this debounce function to our previous implementation and see the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftypeahead-search-with-debouncing-36gzu0%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F36gzu0&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F36gzu0%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/e13afc88718ad672ab38d35fe16e905b/href">https://medium.com/media/e13afc88718ad672ab38d35fe16e905b/href</a></iframe><p>If you check the logs, you can see that we are making fewer API calls than before. Compared to our previous example we are calling the search API only once to search for “hello world”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*g50dbMDze4uArj5qMpJcxQ.png" /><figcaption>Searching “hello world” with debouncing</figcaption></figure><h4>Conclusion</h4><p>Debouncing is a simple yet powerful programming technique. I hope this article helped you understand how debouncing can improve the performance of your web application. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8246cac5b05f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-optimize-typeahead-search-in-your-web-application-8246cac5b05f">How to Optimize Typeahead Search in Your Web Application</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways To Implement Infinite Scroll]]></title>
            <link>https://javascript.plainenglish.io/3-ways-to-implement-infinite-scroll-7b2b7e47d58d?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2b7e47d58d</guid>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 12:38:54 GMT</pubDate>
            <atom:updated>2022-12-27T12:38:54.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*62DQRWno9t2S-OQ2" /><figcaption>Photo by <a href="https://unsplash.com/@veenit_panchal?utm_source=medium&amp;utm_medium=referral">Veenit Panchal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Infinite scroll, commonly used in social media and news feeds, is a web design pattern that allows users to continuously scroll through a list of items, loading new items as the user reaches the bottom of the page.</p><p>With infinite scroll, users don’t need to click a pagination button or navigate to a new page to view more items. Instead, they can simply keep scrolling down the page, and new items will be loaded automatically.</p><p>In this article, we will look at the implementation of infinite scroll using 3 different methods and also the pros and cons of each one.</p><h3>1. Using the scroll event</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll_event">scroll event</a> is a DOM event that is triggered every time the element is scrolled. Other than implementing infinite scroll, you can also use it to update the layout or style of an element based on its scroll position.</p><p>Here is an implementation using scroll event:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Finfinite-scroll-using-scroll-event-sfs15y%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fsfs15y&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fsfs15y%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf8c9b7ddef008bd713729498b47a0b/href">https://medium.com/media/edf8c9b7ddef008bd713729498b47a0b/href</a></iframe><h4>Pros:</h4><ul><li><strong>Simple:</strong> Using the scroll event is a simple approach that can be easy to implement.</li><li><strong>Wide support:</strong> The scroll event is supported in all modern browsers, so you don&#39;t need to worry about compatibility issues.</li></ul><h4>Cons:</h4><ul><li><strong>Bad performance:</strong> Using the scroll event can be inefficient, as it is triggered on every scroll event, regardless of whether the user has reached the bottom of the page. This can be especially problematic for large pages with many elements, as it is bound to cause performance issues.</li><li><strong>Not user-friendly:</strong> Using the scroll event can be less user-friendly, as it does not provide a smooth, continuous experience for the user. The content is loaded in chunks as the user scrolls, which can be jarring.</li></ul><h3>2. Using the wheel event</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event">wheel event </a>is a DOM event that is fired when a user interacts with a scrollable element using a mouse wheel, touchpad, or other scrolling devices. The wheel event is more advanced than scroll event and provides more detailed information about the scroll.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Finfinite-scroll-using-wheel-event-o2nqnd%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fo2nqnd&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fo2nqnd%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/556c586f4ebaf7c8825211e21167d335/href">https://medium.com/media/556c586f4ebaf7c8825211e21167d335/href</a></iframe><h4><strong>Pros</strong></h4><ul><li><strong>Better performance: </strong>Using the wheel event can be more efficient than using the scroll event, as it is triggered only when the user interacts with the page, rather than on every scroll event. This can be especially useful for large pages with many elements, as it can improve the performance of the page.</li><li><strong>User-friendly: </strong>Using the wheel event can provide a smoother, more continuous experience for the user, as the content is loaded as the user scrolls, rather than in chunks.</li></ul><h4>Cons</h4><ul><li><strong>Complex:</strong> Implementing infinite scroll with the wheel event can be more complex than using the scroll event, as you need to handle the different types of user input (e.g., mouse wheel, touchpad, etc.) and ensure that the infinite scroll behaves consistently across devices.</li><li><strong>May not work on all browsers: </strong>The wheel event is still not supported in all browsers, so you may need to include a polyfill to support older browsers.</li></ul><h3>3. Using the IntersectionObserver API</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">IntersectionObserver API</a> allows you to monitor the intersection of an element with its ancestor elements or with a top-level document’s viewport. It is great for implementing infinite scrolling among other things.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Finfinite-scroll-using-intersection-observer-api-ltqoyq%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fltqoyq&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fltqoyq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/285508a750ab93fbea8fdb7dfaba8d9e/href">https://medium.com/media/285508a750ab93fbea8fdb7dfaba8d9e/href</a></iframe><h4>Pros:</h4><ul><li><strong>Best Performance:</strong> The IntersectionObserver API allows you to monitor the intersection of elements with the viewport asynchronously, without constantly polling the scroll position. This can be more efficient than other approaches, especially for large pages with many elements.</li><li><strong>Customizable:</strong> The IntersectionObserver API allows you to customize the threshold for when the intersection is triggered and the root element to which the intersection is relative. This can be useful for fine-tuning the behavior of the infinite scroll.</li></ul><h4>Cons:</h4><ul><li><strong>May not work on all browsers:</strong> Even though the IntersectionObserver API is now supported in the latest version of most browsers, so you may need to include a polyfill if you need to support older browsers.</li></ul><h3>Conclusion</h3><p>Implementing infinite scrolling in a web application can enhance the user experience and each method we covered in this article has its own benefits and drawbacks. The best approach depends on the specific needs and requirements of your application.</p><p>Thank you for reading, and I hope you found this article helpful.</p><h4>More content at <a href="https://plainenglish.io/">PlainEnglish.io</a>.</h4><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><h4>Looking to scale your software startup? Check out <a href="https://circuit.ooo/?utm=publication-post-cta">Circuit</a>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2b7e47d58d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/3-ways-to-implement-infinite-scroll-7b2b7e47d58d">3 Ways To Implement Infinite Scroll</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Create a Custom Typescript Decorator]]></title>
            <link>https://medium.com/geekculture/how-to-create-a-custom-typescript-decorator-c4a1998e1b5e?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4a1998e1b5e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 20:32:17 GMT</pubDate>
            <atom:updated>2022-12-21T20:32:17.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_fxZSvlZHqH6NFrAelv-A.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/jillwellington-334088/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=553457">Jill Wellington</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=553457">Pixabay</a></figcaption></figure><p>If you have been using Typescript for a while then there is a good chance that you have already seen and used decorators in your code. They are the functions that are applied to classes, methods, properties, or method parameters using the @ symbol followed by the decorator function name.</p><h4>What are they used for?</h4><p>TypeScript decorators are a feature of TypeScript that allows you to attach metadata to classes, methods, and properties, and execute logic when the decorated element is accessed or modified. They are a good way to modify the behavior of a class or its members at runtime, without changing the implementation of the class itself.</p><p>They can be used for a wide range of tasks, such as:</p><ul><li>Adding additional behavior to a class or its members</li><li>Implementing dependency injection</li><li>Modifying third-party libraries without having to change the implementation of the library itself.</li></ul><h4>Components of a decorator</h4><p>In this article, We will be creating a memoize method decorator that will help us cache the output of our function call to better optimize our code.</p><p>Before we get to that, let&#39;s see in detail the components of a method decorator:</p><p>The decorator function takes three parameters:</p><ol><li>target: This is the object that the decorator is being applied to. In the case of a method decorator, it will be the prototype of the class that the method belongs to.</li><li>key: This is the name of the decorated property or method. In the case of a method decorator, it will be the name of the method.</li><li>descriptor: This is an object that contains information about the decorated property or method, such as its value and any other properties.</li></ol><h4>Let’s get started!</h4><p>Now that we have a general idea of what a decorator consists of, let&#39;s start by defining our memoize decorator. The purpose of memoize is to cache the results of previous function calls and use the previous result for subsequent calls with the same arguments. To do that, we will be using a Map object to store a key value map of arguments and output in memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30316d880f3cb4020306ac3ddffa5d22/href">https://medium.com/media/30316d880f3cb4020306ac3ddffa5d22/href</a></iframe><p>Next, we will modify the value property of the descriptor object to wrap the original method in a new function that will return the cached value if it exists and also store the new function call results in the cache. Finally, we return the modified descriptor object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb58de7685a4d3f0f25b954f72bb388b/href">https://medium.com/media/bb58de7685a4d3f0f25b954f72bb388b/href</a></iframe><p>We are now done with our custom decorator. The next step will be to test it out!</p><p>Let’s create a class with a recursive implementation of the Fibonacci sequence algorithm and add our decorator to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d185dfcb5a667466c5388b85d12f579/href">https://medium.com/media/1d185dfcb5a667466c5388b85d12f579/href</a></iframe><p>Running this code you should see the following output on the console:</p><pre>1<br>1<br>2<br>3<br>5<br>8<br>13<br>21<br>34<br>55<br>89<br>144</pre><p>Perfect, you could also check by running the code without the memoize decorator, then it will take a very long time to finish.</p><h4>Are there any downsides?</h4><p>There are a few limitations to TypeScript decorators that you should be aware of. The first thing to note is that they are not a part of the Javascript language, so you can only use them with Typescript only.</p><p>Another thing to keep in mind when creating custom decorators is to use them for relatively simple and straightforward tasks as they might not be well-suited for modifying the behavior of classes or methods in an easily understandable or predictable way.</p><h4>Conclusion</h4><p>Well, that’s all for this article. I hope you gained some insights about Typescript decorators and how you could potentially leverage them on your next project. You can find the full source code <a href="https://replit.com/@eyuelberga/TypescriptDecoratorDemo?v=1">here</a>. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4a1998e1b5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-create-a-custom-typescript-decorator-c4a1998e1b5e">How To Create a Custom Typescript Decorator</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an Image Watermarking Tool with HTML Canvas]]></title>
            <link>https://javascript.plainenglish.io/how-to-build-an-image-watermarking-tool-with-html-canvas-9dd45bb4f13?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd45bb4f13</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 16:03:03 GMT</pubDate>
            <atom:updated>2022-03-07T16:03:03.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fVBwPubEojQ8fQhD" /><figcaption>Photo by <a href="https://unsplash.com/@mihodango?utm_source=medium&amp;utm_medium=referral">Ho Hyou</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>HTML Canvas is a very versatile element that can be used for drawing, animation, and image manipulation. In this article, We will build an In-browser tool you can use to add watermarks to images. We will use vanilla JavaScript and Bootstrap for styling.</p><p>We will cover some of the basics of HTML Canvas, like drawing, positioning, and also saving images. If you are new to the Canvas API, this will be a nice tutorial to get started.</p><h3>What we are going to build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAHaU9ZQbwNXlnMDhca3Ag.png" /></figure><p>The UI is very straightforward. We have two file inputs for uploading the base image(the image we will watermark) and another one for the image that will be placed on top of our first image. We also have options for resizing the images, changing the position and transparency of the watermark. Looks simple right! Let&#39;s start coding.</p><blockquote>P.S. If you want to take a look at a live demo, you can find it <a href="https://eyuelberga.github.io/HTMLCanvasImageWatermarker/">here</a>.</blockquote><h3>Creating a new project</h3><p>We will be using <a href="https://vitejs.dev/">Vite</a> for this, but a simple HTML and a Javascript file will also do. If you don’t want to get into setting up a development server, you can skip this step. I prefer to work with a dev server, to benefit from fun features like hot-reloading.</p><p>To create a new project just run:</p><pre>$ yarn create vite</pre><p>It will prompt you to fill in a project name and a framework. You should select <strong>vanilla, </strong>we will only be using plain JavaScript.</p><p>Once this is done we can start our dev server using:</p><pre>$ yarn dev</pre><h3>The web interface</h3><p>We will start with the HTML page. If you followed the previous step, the file index.html already exists at the root of the project folder.</p><p>The first thing we need to do is add Bootstrap stylings to our HTML file. Go to the <a href="https://getbootstrap.com/">Bootstrap home page</a> and in the installation section, you will find a code snippet for the CSS files. We need to add this to our head tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b634381d70436d07c235a38a13c0eb5/href">https://medium.com/media/3b634381d70436d07c235a38a13c0eb5/href</a></iframe><p>We can now add the body of our HTML, using different components from Bootstrap. If you want to learn more, you can check out the <a href="https://getbootstrap.com/docs/5.1/getting-started/introduction/">Docs</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5727783d8d1de04d33c16171e329ffac/href">https://medium.com/media/5727783d8d1de04d33c16171e329ffac/href</a></iframe><h3>The JavaScript part…</h3><p>We will put all our JavaScript code into a file named main.js. We will start by creating small functions that will perform specific tasks and we’ll bring them all together at the end.</p><h4>Reading local images</h4><p>We will define a function getImage that will read the selected file from the input, create a new HTMLImageElement instance, and invoke a callback function when the image is finished loading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2cee7de327b2fc4873ae4e0320528f2/href">https://medium.com/media/b2cee7de327b2fc4873ae4e0320528f2/href</a></iframe><h4>Adjusting image size</h4><p>We have an option in the UI to adjust the size of the image. We also have a checkbox to toggle between maintaining the aspect ratio during resize. So how do we implement that?</p><blockquote>The <strong>aspect ratio</strong> of an image is just the ratio of its width to its height.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9851bdd75b725ebc9797d3e57725dd88/href">https://medium.com/media/9851bdd75b725ebc9797d3e57725dd88/href</a></iframe><p>We will define three functions:</p><ul><li><strong>getAspectRatio</strong>: will return the aspect ratio of an image given width and height</li><li><strong>getWidthFromRatio</strong>: will return width, given the height and aspect ratio of the image</li><li><strong>getHeightFromRatio</strong>: will return height, given the width and aspect ratio of the image</li></ul><p>Now that we have these functions defined, we can add two more methods to change the image’s width and height.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ab4455805ebf771d999c3292432ed1/href">https://medium.com/media/85ab4455805ebf771d999c3292432ed1/href</a></iframe><p>The two functions have similar parameters. The image argument will take an HTMLImageElement, which has a width and height property. If the value of maintainAspectRatio is true, the image should also scale based on the aspect ratio. So, we will use the functions we defined earlier to find the right dimensions based on the aspect ratio value.</p><h4>Positioning the watermark image</h4><p>To position an image on the canvas, we first need to understand how canvas coordinates work. Unlike the cartesian coordinate system we are used to in mathematics, the origin point (0,0) in the HTML Canvas coordinate is located at the upper left corner. The positive x-axis extends to the right and the positive y-axis, downwards. So, drawing an image on the canvas requires setting an x and y coordinate in which the top-left corner of the image will be placed.</p><p>Keeping this point in mind, if we know the size of the watermark image and the canvas, we calculate the coordinate values for different positions. Here is a diagram that will make it a little clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*dd9ZOmsMTzYaOzRanVGLTg.png" /><figcaption>watermark position and coordinate values</figcaption></figure><p>So, the coordinate values highlighted in yellow would the ones we need to draw the watermark image in those positions. Okay, let’s write a function that will do the job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b576237f0e644f247f75a5951ee255/href">https://medium.com/media/e5b576237f0e644f247f75a5951ee255/href</a></iframe><h4>Let’s watermark</h4><p>Till now we haven’t written any code that interacts with the Canvas API. Now let’s get into writing the function that will do the watermarking for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766064d942890e3823aec0c5797bdd20/href">https://medium.com/media/766064d942890e3823aec0c5797bdd20/href</a></iframe><p>The first thing we do is get the 2D rendering context from the canvas. This allows us to draw our images. Then we set the canvas width and height to the same dimensions as our base image. We are also using the clearRect method to always draw on a clear canvas every time the function is called.</p><p>Next, we call drawImage to draw our base image to the canvas. Then before we draw our watermark image onto the canvas, we set a new globalAlpha value, to add transparency to the image. We are also using the getCoordinates method here to get the x and y coordinates for the watermark image based on the position we want.</p><h4>Saving the Image</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3013f70b5c504cb8878efea026ce0ac/href">https://medium.com/media/e3013f70b5c504cb8878efea026ce0ac/href</a></iframe><p>To save the image, we first get the image data from the canvas and then create a link and then programmatically click it. To get the image data we call the toDataURL method on the canvas.</p><h4>Some utility functions</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2221c472ce6f63840f760499cba6a6bd/href">https://medium.com/media/2221c472ce6f63840f760499cba6a6bd/href</a></iframe><p>The updateImageSizeValueDOM method will update the width and height input values on the DOM based on the current image dimensions.</p><p>The isChecked method returns a boolean based on the checkbox’s current state.</p><h4>Bringing it all together</h4><p>So, we’re done with defining all the methods we need, the next step would be to call these them based on user interaction.</p><p>First, let’s get references to all elements we need from the DOM and store them as variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c4d1d4623635d34bea02be2161c8a4c/href">https://medium.com/media/4c4d1d4623635d34bea02be2161c8a4c/href</a></iframe><p>We also need to initialize some variables to store the images and their initial aspect ratios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e527486265ba9d2e46c36f0060d0ad8e/href">https://medium.com/media/e527486265ba9d2e46c36f0060d0ad8e/href</a></iframe><p>Next, we need to listen to new input events on the file input elements and update our image and aspect ratio variables. We use the getImage function we wrote earlier here to get image data from the input event. We also need to update the width and height values in the DOM, so we will use our updateImageSizeValueDOM function here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7950dc802a399a4f9d85e333567a841/href">https://medium.com/media/e7950dc802a399a4f9d85e333567a841/href</a></iframe><p>We now add event listeners to the height and width inputs to resize the image. Here we will be using the changeImageHeight and changeImageWidth methods to adjust the dimensions of the image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb735b12307be66b5715d48acce6d606/href">https://medium.com/media/fb735b12307be66b5715d48acce6d606/href</a></iframe><p>Finally, we will add click event handlers to our watermark and save buttons.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e08f7b4c067c3030c4664590961e59/href">https://medium.com/media/d7e08f7b4c067c3030c4664590961e59/href</a></iframe><h3>We are done!</h3><p>If you like to take a look at the source code, it is available on <a href="https://github.com/eyuelberga/HTMLCanvasImageWatermarker">Github</a>. Hope you enjoyed this article. Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd45bb4f13" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-build-an-image-watermarking-tool-with-html-canvas-9dd45bb4f13">How to Build an Image Watermarking Tool with HTML Canvas</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Things You Should Know about Memoization in React]]></title>
            <link>https://javascript.plainenglish.io/3-things-you-should-know-about-memoization-in-react-b2f09570bb53?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f09570bb53</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 07:17:49 GMT</pubDate>
            <atom:updated>2022-02-28T07:17:49.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>The 3 things every developer should be aware of, before using memoization methods in a React project.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*A1FHOYfRbkuiOquS4U69hg.jpeg" /></figure><p>Memoization is a technique of caching the results of a computationally expensive function. In React we can use this technique to avoid unnecessary re-renders and expensive recomputations. React provides three methods for this:</p><ul><li><strong>memo</strong>: a higher-order component used for memoizing components.</li><li><strong>useMemo</strong>: hook for memoizing a value which is expensive to compute</li><li><strong>useCallback</strong>: similar to useMemo, used for memoizing a callback function.</li></ul><p>Even though memoization is great for improving performance, if used inappropriately it can have the opposite effect. Let’s look at the top three things you should be mindful of before using these methods in your React projects.</p><h3>1. Memoization is meant for performance optimization</h3><p>Unless you encounter performance issues in your application, it is probably not a good idea to use any of the memoization methods. Your code should work without memoization(however slow it may be). As a rule of thumb, you should consider optimizing after implementing your components.</p><p>If you notice performance issues, the React DevTools can help in finding performance bottlenecks. But also keep in mind that all performance issues can’t be solved with memoization. So it is best to always check if there is any improvement gained from it.</p><p>Also, be wary of premature optimization, so you don’t waste time optimizing without the need for it. Most operations in JavaScript are optimized and overall the React framework is very performant. So, in most cases, further optimization might not be needed.</p><h3>2. Memoization has performance overheads</h3><p>Performance optimizations mostly come with some trade-offs. This is especially true with memoization. By caching previous results, we are using more memory in turn for better speed. So, you should always consider if the cost of memoization is worth it. This depends on the use case, but it is worth noting that there can be an extra overhead to its use if performance improvements are not substantial.</p><h3>3. React doesn’t always guarantee memoization</h3><p>On the React docs if you see the section on <a href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a> it reads:</p><p>You may rely on useMemo as a performance optimization, not as a semantic guarantee.</p><p>If you also look at <a href="https://reactjs.org/docs/react-api.html#reactmemo">React.memo</a> in the docs you will find this:</p><p>This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.</p><p>React will cache results for as long as possible, but in some cases, it may also choose to invalidate the cache. So, there is no guarantee that the memoized value has not been discarded. This means you can’t rely on React to always memoize values for you. To avoid introducing bugs to your application, always use memoization methods to optimize performance and nothing more.</p><h3>Conclusion</h3><p>I hope you now have all the information you need to use memoization in React responsibly. Please do share your comments and suggestions, and thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f09570bb53" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/3-things-you-should-know-about-memoization-in-react-b2f09570bb53">3 Things You Should Know about Memoization in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Shouldn’t be Using Mixins in Vue.js Anymore]]></title>
            <link>https://javascript.plainenglish.io/you-shouldnt-be-using-mixins-in-vue-js-anymore-ec8c09824f9f?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec8c09824f9f</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 14:21:59 GMT</pubDate>
            <atom:updated>2022-01-10T14:21:59.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fcTAP9ZhXAVVN2mB" /><figcaption>Photo by <a href="https://unsplash.com/@greysonjoralemon?utm_source=medium&amp;utm_medium=referral">Greyson Joralemon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Mixins were the go-to way of sharing reusable logic between components in Vue 2. But now with the availability of the Composition API, we can achieve code reusability in a much cleaner way.</p><h3>What are mixins?</h3><p>Mixins are a way of reusing a functionality between components by merging the properties of a mixin with the component. It allows us to define a certain logic once and use it on multiple components.</p><h3>Why Shouldn’t I use mixins?</h3><p>Well, mixins are generally not the ideal way of sharing logic because they come with some drawbacks:</p><h4>Overlapping names</h4><p>Naming conflicts often arise with mixins. During the merging process, conflicting properties between mixins and components get overridden based on some merge strategy. This can lead to some unexpected behaviors in our application.</p><h4>Tight coupling</h4><p>It is not uncommon to encounter implicit dependencies between a mixin and a component. This makes it excruciatingly hard to refactor the component or mixin without breaking the existing code. Mixins can also get tightly coupled to other mixins over time as new requirements emerge.</p><h4>Hard to understand and debug</h4><p>It is very difficult for a new developer to understand a code-base with lots of mixins. It is not obvious from where a property is coming from, especially if there are globally registered mixins. Isolating a bug also becomes a nightmare as the application grows.</p><h3>Replacing mixins with composables</h3><p>Let’s start with an example to illustrate some of the flaws of mixins and how we would solve these issues with the Composition API.</p><p>Say we have a simple count-down timer to wait for some seconds before showing the main contents of a component. We have extracted this logic to a mixin called countDownMixin . This is what the code looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ccb7e23427dcd9c10c8c672c5fc7182/href">https://medium.com/media/8ccb7e23427dcd9c10c8c672c5fc7182/href</a></iframe><p>By registering this mixin, we will be able to “mix” the count-down logic to the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9344cdaf8f5e0d8a59094145c2797c12/href">https://medium.com/media/9344cdaf8f5e0d8a59094145c2797c12/href</a></iframe><p>This seems to be a neat solution at first glance, but what if I want to wait for 20 seconds instead of 10?</p><p>Well, one solution would be to override the initial state of countDown from the consuming component. By doing that, we explicitly create conflicting names knowing that the data property defined in the component will be given top priority.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f110390e9ab14db3a676565bc3e5939/href">https://medium.com/media/0f110390e9ab14db3a676565bc3e5939/href</a></iframe><p>This solution works, but having the ability to do this makes the mixin vulnerable to unintentional replacement of other options too. Now, if the component defines a decrement method without knowing that the countDownMixin also has a method with the same name, the component will not work as expected anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77cec4ebe25af75373a6c3d8e3b424c4/href">https://medium.com/media/77cec4ebe25af75373a6c3d8e3b424c4/href</a></iframe><p>Although the decrement method is defined for the purpose of internal use only, it is not possible to avoid it from being overridden.</p><h4>A better solution with the Composition API</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b34dd4ec7c2da280e1eb25a0ba064c0f/href">https://medium.com/media/b34dd4ec7c2da280e1eb25a0ba064c0f/href</a></iframe><p>By using the Composition API, we avoid all of the problems we faced with mixins. The useCountDown composable takes as a parameter the count down duration. There is no need to override anything and dependencies are neatly organized as parameters of the composable function.</p><p>It also exposes properties only intended to be used by the consuming component and the internal states are protected, so the component cannot accidentally alter the behavior of the composable.</p><p>Name overlaps are also not an issue, as we are required to explicitly provide names for all the returned variables of the composable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d5c877ec8abded95088c1199b70c77d/href">https://medium.com/media/0d5c877ec8abded95088c1199b70c77d/href</a></iframe><h3>Closing thoughts</h3><p>The Composition API makes code reuse very easy and straightforward. I hope you found this article convincing enough to migrate from mixins and embrace the power of composables. If you need more information on the Composition API, please check out the <a href="https://v3.vuejs.org/guide/composition-api-introduction.html">Official Docs</a>. Thank you for reading.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec8c09824f9f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/you-shouldnt-be-using-mixins-in-vue-js-anymore-ec8c09824f9f">You Shouldn’t be Using Mixins in Vue.js Anymore</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid Memory Leaks in your React App by canceling API calls]]></title>
            <link>https://medium.com/geekculture/avoid-memory-leaks-in-your-react-app-by-canceling-api-calls-9cf692c06573?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cf692c06573</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 10:03:56 GMT</pubDate>
            <atom:updated>2021-10-29T10:03:56.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qbW-3prta82yTJWA" /><figcaption>Photo by <a href="https://unsplash.com/@sanatoga?utm_source=medium&amp;utm_medium=referral">Joe Zlomek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*z_-fJYFHALIfUpDYr8u6QQ.png" /></figure><p>Surely you have encountered this warning while working on a React app. Even though the JavaScript language has an automated memory management mechanism, it is still possible for memory leaks to happen if we are not careful of how we implement our programs. The same applies to a React application. Memory leaks are not a good sign and should always be avoided.</p><p>The most easily overlooked cause for memory leaks would be improper handling of API calls. Because calls to an API are asynchronous, it is possible for the component that initiated the task to be unmounted before the request finishes. This can happen for instance, when a user goes to another page while the current page has not finished loading.</p><h3>A Demo</h3><p>To demonstrate, lets use a simple React app which has two components, Home and About and also a button to toggle between the two. The Home component fetches blog post data from an API that we’ll setup using json-server. We will also delay our server’s response time to 3 seconds, so that we have enough time to switch between the two components before the API request completes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15bc48b80f0338c5532346a7622f2734/href">https://medium.com/media/15bc48b80f0338c5532346a7622f2734/href</a></iframe><p>In our App.jsx we have a button which toggles the isHome state and conditionally render either the Home or the About component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba8735debfff2ff5a65409576b940e0/href">https://medium.com/media/5ba8735debfff2ff5a65409576b940e0/href</a></iframe><p>The Home component fetches the blog post data from our API server during initial render.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad7bafd2bd700705ac7783a84306dd22/href">https://medium.com/media/ad7bafd2bd700705ac7783a84306dd22/href</a></iframe><p>The About component just contains some text to be rendered in the DOM.</p><p>We also need to add json-server and configure it in our package.json file with 3 seconds response delay.</p><pre>{<br> &quot;scripts&quot;:{<br>     ...<br>    &quot;server&quot;: &quot;json-server --watch db.json --port 3001 --delay 3000&quot;<br>}<br>}</pre><p>Now, if we run our project and click on the “About Page” button while loading is in progress, we will get a memory leak warning on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zYYGTaPoIBOLQliFQsyvBw.gif" /><figcaption>Memory leak warning shows up on the console</figcaption></figure><h3>The Solution</h3><p>A way to fix this issue is to cancel the API request when the useEffect cleanup function is called. The preferred way of canceling a request would be to use the AbortController as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">Web API documentation</a>. The AbortController will allow us to abort the web request by passing the AbortSignal to the fetch method and then calling abort before the component is unmounted.</p><p>We need make slight modifications to our Home component to avoid the memory leak problem. We initialize a new AbortController instance and pass the signal from the controller to our fetch method as a signal property. Then we call controller.abort on the return function of our useEffect hook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4313e4de444cee5e8e19a3709b0d5c13/href">https://medium.com/media/4313e4de444cee5e8e19a3709b0d5c13/href</a></iframe><p>Now, if we try the same thing as before and switch to the About component while loading is in progress the memory leak warning will not show up in the console.</p><h3>Conclusion</h3><p>Well that’s it for this article. Hope you enjoyed reading it. You can find the source code for the demo <a href="https://github.com/eyuelberga/react-memory-leak-demo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf692c06573" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/avoid-memory-leaks-in-your-react-app-by-canceling-api-calls-9cf692c06573">Avoid Memory Leaks in your React App by canceling API calls</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify State Management in React with the useReducer Hook]]></title>
            <link>https://javascript.plainenglish.io/simplify-state-management-in-react-with-usereducer-hook-bea33fc17018?source=rss-4106ccb20b99------2</link>
            <guid isPermaLink="false">https://medium.com/p/bea33fc17018</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Eyuel Berga Woldemichael]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 11:00:31 GMT</pubDate>
            <atom:updated>2021-07-13T21:31:08.881Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use the ‘useReducer’ hook in React to refactor useState and simplify state management.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQBT_k7dowZaS1Ls" /><figcaption>Photo by <a href="https://unsplash.com/@yanots?utm_source=medium&amp;utm_medium=referral">Yan Ots</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we have simple state management problems useState is the appropriate hook to use. But, sometimes managing state can be complex if we have multiple state variables that change on the same event. For such cases, the useReducerhook should be the preferred option.</p><p>In this article, we will look at a simple Todo app that uses useState and refactor it to use the useReducer hook instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ORBLoR3o_qjm4dOXPfGFOw.gif" /><figcaption>Todo list application</figcaption></figure><p>The main component for our app currently looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcd673f67bdc44ccfb78fdc2965cab66/href">https://medium.com/media/fcd673f67bdc44ccfb78fdc2965cab66/href</a></iframe><p>We have to manage three states in our app; todos , status and error. The status state tracks whether our network request is loading or returned a successful or an error response. So, when making requests we update both error and status or todos and status at the same time. Instead of doing multiple state updates, it would be easier to encapsulate the state logic in a reducer.</p><p>A <strong>reducer </strong>is basically a function that takes in an old state along with an action and returns a new state. Our reducer will manage state updates for four actions. We will use a switch statement to conditionally handle our actions. We pass all response payloads and the action type through the action argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7790a195e91af483b47c37626809da6/href">https://medium.com/media/d7790a195e91af483b47c37626809da6/href</a></iframe><p>Each time we return a new state, we concatenate it with the prior state using the spread operator and change only the values we wish to modify. Our final reducer function looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2a573230f65eea4837a39eacb490b9/href">https://medium.com/media/ea2a573230f65eea4837a39eacb490b9/href</a></iframe><p>Now that we have defined our reducer function, we can refactor our main component to use the useReducer hook.</p><p>The first thing to change is the initialization of our state. The useReducer hook takes in our reducer function and initial states. We also destructure the output to state variable and the dispatch function, which we use to trigger state changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c37f6cd60334def7062232b9b5531b/href">https://medium.com/media/38c37f6cd60334def7062232b9b5531b/href</a></iframe><p>When making state changes, we use the dispatch function by passing in the action type and some additional data.</p><p>This is how we trigger a state update when todos have been successfully fetched from the server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18de27b5e43150af14582184e82fb3de/href">https://medium.com/media/18de27b5e43150af14582184e82fb3de/href</a></iframe><p>After replacing all useStatecalls withuseReducer, our refactored App.js file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4694fd599de47c192b1eaf08effa1dd/href">https://medium.com/media/d4694fd599de47c192b1eaf08effa1dd/href</a></iframe><p>That’s all for this article. Hope you enjoyed reading it. You can find the full source code <a href="https://github.com/eyuelberga/use-reducer-demo">here</a>.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bea33fc17018" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/simplify-state-management-in-react-with-usereducer-hook-bea33fc17018">Simplify State Management in React with the useReducer Hook</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>