<?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 Rajesh Bhattarai on Medium]]></title>
        <description><![CDATA[Stories by Rajesh Bhattarai on Medium]]></description>
        <link>https://medium.com/@rajeshi?source=rss-df6dad62b19b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0QhVnDGqOjz6sfUxLgxHGg.jpeg</url>
            <title>Stories by Rajesh Bhattarai on Medium</title>
            <link>https://medium.com/@rajeshi?source=rss-df6dad62b19b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:37:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajeshi/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[Frontend Performance Handbook — Best Practices and Strategies]]></title>
            <link>https://javascript.plainenglish.io/frontend-performance-handbook-best-practices-and-strategies-d86ca9bdb624?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86ca9bdb624</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-performance]]></category>
            <category><![CDATA[frontend-interviews]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 08:03:16 GMT</pubDate>
            <atom:updated>2025-03-31T00:18:28.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Frontend Performance Handbook — Best Practices and Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErZ9eMxHg1W4LEH2YR2jzQ.png" /></figure><p>Frontend performance optimization is one of those tricky areas that even senior developers often struggle with. In this blog, I’ll break it down in-depth, covering everything from fundamentals to advanced strategies. Whether you’re a junior or a seasoned developer, there’s something here for you to learn.</p><h3>The three key areas for optimizing a web app’s performance are:</h3><ol><li><strong>Client-Side</strong> — Optimizing how the browser processes and renders content.</li><li><strong>Network Performance (File Transfer)</strong> — Reducing load times through efficient data transfer.</li><li><strong>Frontend Infrastructure &amp; Build Optimization</strong> — Enhancing performance with CDNs, caching, and efficient build processes.</li></ol><h3>Client Side Performance Optimization</h3><p>There are several client-side optimization techniques:</p><h4><strong>1. Asset Optimization (Optimizing media and static files)</strong></h4><p>Below are some assets optimizing techniques:</p><p><strong>a) Use Modern Image Formats:</strong> WebP and AVIF are lightweight alternatives to traditional formats like JPG and PNG. These formats can achieve smaller file sizes without compromising image quality, making them ideal choices for faster loading times. Additionally, consider compressing your images to reduce file size without sacrificing quality. For images with fewer colors, SVG is an excellent option since it’s extremely lightweight.</p><p><strong>b) Implement Responsive Images (srcset, sizes):</strong> The srcset attribute allows you to define multiple image sizes for different screen resolutions, so the browser can select the best one based on the device’s display. The sizes attribute helps the browser understand how much space the image will occupy, allowing it to choose the right size accordingly. Together, these techniques ensure that images load faster and look sharper across different devices.</p><pre>&lt;img src=&quot;image.jpg&quot; <br>     srcset=&quot;image-small.jpg 600w, image-large.jpg 1200w&quot; <br>     sizes=&quot;(max-width: 600px) 100vw, 50vw&quot; <br>     alt=&quot;A responsive image&quot; /&gt;</pre><p><strong>c) Font Optimization:</strong> Use modern font formats like WOFF2 for better compression and faster loading compared to older formats like TTF or OTF. Set the font-display property to swap or fallback to avoid the “flash of invisible text” (FOIT), which ensures that text is displayed with a fallback font while the custom font loads. Additionally, use the &lt;link rel=”preload”&gt; tag to preload essential fonts, so they start downloading earlier, reducing the time before they’re available for rendering.</p><p><strong>d) Deliver Assets via a CDN:</strong> A Content Delivery Network (CDN) distributes your files (images, scripts, styles) across multiple global servers. This allows users to download assets from a server closer to their location, boosting load speed and enhancing global performance.</p><h4>2. Code Optimization</h4><p>Below are some code optimization techniques:</p><p><strong>a) Code Splitting:</strong> Implement code splitting to load only the necessary JavaScript for each route. This reduces the amount of JavaScript the browser has to download, improving load times. In React, you can use React.lazy to split your code.</p><pre>const About = React.lazy(() =&gt; import(&#39;./About&#39;));<br><br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;About /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p>In this example, the About component will only load when it’s needed (i.e., when the user navigates to it), reducing the initial load time.</p><p><strong>b) Lazy Loading:</strong> Implement lazy loading for components and images below the first fold. This means only the content visible in the user’s viewport will be loaded initially, and the rest will load as the user scrolls. This improves performance and reduces initial page load time.</p><pre>const App = () =&gt; (<br>  &lt;div&gt;<br>    &lt;img src=&quot;image.jpg&quot; alt=&quot;Lazy loaded image&quot; loading=&quot;lazy&quot; /&gt;<br>  &lt;/div&gt;<br>);</pre><p>This ensures that the image is only loaded when it comes into view. For a particular component or section to lazy-load, you can create your custom component like “LazyLoad”, which uses the Intersection Observer to detect if the component is in the visible area or close to it, and then renders it. I see many developers relying on third-party packages to lazy-load sections; however, you can achieve this yourself, saving the need to add extra libraries or unwanted chunks.</p><p><strong>c) Avoid Unnecessary Re-renders:</strong> Hooks like <strong>useRef()</strong> are often underused but can significantly improve performance. When tracking state that doesn&#39;t need to trigger re-renders (e.g., form validation or DOM references), use <strong>useRef()</strong> instead of <strong>useState()</strong>. <strong>useState()</strong> should only be used when you need to update the UI. Always ask yourself, &quot;Do I need to update the UI?&quot; before using <strong>useState()</strong>. If the answer is yes, then use it; otherwise, opt for a simple variable or <strong>useRef()</strong>.</p><pre>import React, { useRef } from &#39;react&#39;;<br><br>const FormComponent = () =&gt; {<br>  const inputRef = useRef();<br><br>  const handleSubmit = () =&gt; {<br>    // Access value without causing a re-render<br>    console.log(inputRef.current.value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} placeholder=&quot;Enter text&quot; /&gt;<br>      &lt;button onClick={handleSubmit}&gt;Submit&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FormComponent;</pre><p><strong>d) Optimize React Components</strong>: Use <strong>performance-focused hooks</strong> like <strong>useMemo()</strong>, <strong>useCallback()</strong>, and <strong>React.memo()`</strong> to prevent unnecessary re-renders and optimize rendering performance. Each of them has its unique use case, which you can read about in the <a href="https://medium.com/@rajeshi/list/learn-react-hooks-6378a2e32c7c">articles </a>I have provided.</p><p><strong>e) Minify HTML, CSS, and JavaScript:</strong> Use bundlers like <strong>Webpack</strong> or <strong>Vite </strong>to minify your code, reducing file sizes and speeding up delivery over the network. Minification removes unnecessary spaces, and comments, and simplifies variable names. I will discuss more about it in the Build Optimization section.</p><pre>module.exports = {<br>  mode: &#39;production&#39;,<br>};</pre><p>If you’re using Webpack 5 in <strong>production </strong>mode, the minification process will automatically be handled unless you override the configuration.</p><p><strong>f) Optimize API Calls: </strong>Whenever you integrate an API, make it a habit to open the <strong>Network tab</strong> in Chrome DevTools to check if the API is being called more than once unnecessarily. If you notice multiple redundant calls, you can use <a href="https://medium.com/dev-genius/optimize-your-api-by-canceling-it-abortcontroller-in-javascript-d9a5428988b8"><strong>AbortController</strong></a> to cancel the unwanted request. Additionally, if you&#39;re making multiple independent API calls, use <strong>Promise.allSettled()</strong> to run them concurrently and handle all responses at once.</p><p>Example using <strong>AbortController</strong> to cancel redundant API calls:</p><pre>const controller = new AbortController();<br>const signal = controller.signal;<br><br>// Start the API request<br>fetch(&#39;https://api.example.com/data&#39;, { signal })<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(&#39;Request failed&#39;, error));<br><br>// Abort the request if needed (e.g., before making a new one)<br>controller.abort();</pre><p>Example using <strong>Promise.allSettled()</strong> to make concurrent API calls:</p><pre>const urls = [<br>  &#39;https://api.example.com/data1&#39;,<br>  &#39;https://api.example.com/data2&#39;,<br>  &#39;https://api.example.com/data3&#39;<br>];<br><br>const results = await Promise.allSettled(urls.map(url =&gt; fetch(url)));<br><br>results.forEach((result, index) =&gt; {<br>  if (result.status === &#39;fulfilled&#39;) {<br>    const data = await result.value;<br>    console.log(`Data from URL ${index + 1}:`, data);<br>  } else {<br>    console.error(`Error fetching from URL ${index + 1}:`, result.reason);<br>  }<br>});</pre><p><strong>g) Semantic HTML: </strong>Using appropriate semantic tags not only provides SEO benefits but also eliminates the need for excessive &lt;div&gt; and &lt;span&gt;, making the DOM tree shallower. A less complex DOM improves rendering speed and simplifies JavaScript DOM manipulation. <a href="https://www.youtube.com/watch?v=TnYT5aXBAh0">This video</a> demonstrates it well.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTnYT5aXBAh0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTnYT5aXBAh0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTnYT5aXBAh0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6aca1db50a4aa3294291a185b27e2d/href">https://medium.com/media/2d6aca1db50a4aa3294291a185b27e2d/href</a></iframe><h4>3. Rendering Patterns</h4><p>A rendering pattern refers to the way in which HTML, CSS, and JavaScript code are processed and rendered in a web application.</p><p>When building a web app, one of the key decisions you’ll face is: “Where and how should I render the content?” Should it be done on the web server, during the build process, at the edge, or directly in the client’s browser? Should the content load all at once, in parts, or progressively?</p><p>Choosing the right rendering pattern can optimize build times, enhance loading performance, and keep processing costs low. Each rendering approach serves different goals, balancing performance and user experience in distinct ways.</p><p><strong>Server-Side Rendering (SSR):</strong> With SSR, the web server creates the HTML for a page and sends it to the browser. This method can improve initial load times and help with SEO, but it can be slower when dealing with dynamic content that changes often.</p><p><strong>Client-Side Rendering (CSR):</strong> In CSR, the browser builds the HTML using JavaScript. This can lead to a faster, more interactive experience for the user, but the page may take longer to load initially, and it’s not the best for SEO.</p><p><strong>Static Site Generation (SSG):</strong> With SSG, the HTML is generated during the build process and served as a static file to the client. This provides fast performance and better security but isn’t as flexible for pages that need to change frequently.</p><p><a href="https://www.youtube.com/watch?v=SLQa-XdDOtk">Watch this video</a> for a complete explanation of rendering patterns.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSLQa-XdDOtk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSLQa-XdDOtk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSLQa-XdDOtk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/859ecff9e14e494db5581ebf58fef349/href">https://medium.com/media/859ecff9e14e494db5581ebf58fef349/href</a></iframe><h4>4. Critical Rendering Path (CRP):</h4><p>The Critical Rendering Path (CRP) refers to the steps the browser takes to turn HTML, CSS, and JavaScript into visible content on the screen. By optimizing the critical render path, you can improve how quickly the page loads. The CRP includes processes like building the Document Object Model (DOM), the CSS Object Model (CSSOM), creating the render tree, and performing the layout.</p><p>Below are different strategies to Optimize the Critical Rendering Path:</p><p><strong>HTML Optimization:</strong></p><p><strong>i) Load &lt;style&gt; in &lt;head&gt;:</strong> This ensures that the styles are applied before the content is visible, preventing a flash of unstyled content (FOUC).</p><p><strong>ii) Load &lt;script&gt; right before &lt;/body&gt;:</strong> This minimizes render blocking and allows the HTML content to load before JavaScript runs.</p><p><strong>CSS Optimization:</strong></p><p><strong>i) Load only what is needed:</strong> Only include the necessary CSS for the page being loaded to avoid excess styles that slow down rendering.</p><p><strong>ii) Use less specificity:</strong> Simplify your CSS selectors to make it easier for the browser to apply styles, speeding up the rendering process.</p><p><strong>JavaScript Optimization:</strong></p><p><strong>i) Load scripts asynchronously:</strong> This ensures that JavaScript is loaded in parallel without blocking the page from rendering.</p><p><strong>ii) Defer loading of scripts:</strong> Delays the execution of non-essential scripts until the page has finished loading, improving the initial render time.</p><p><strong>Third-Party Optimization: </strong>Third-party services like Google Analytics, GTag Manager, or Microsoft Clarity can slow down the page load and impact user experience. Here are a few ways to optimize them:</p><p><strong>a) Load their scripts with defer:</strong> This ensures the scripts load after the main content is rendered.</p><p><strong>b) Load them when the user scrolls:</strong> This technique delays loading third-party scripts until the user interacts with the page, reducing the initial load time.</p><p><strong>c) Use setTimeout to load after a delay:</strong> Load third-party scripts after a specified time (e.g., 5 seconds), ensuring they don’t delay the initial render.</p><p><strong>d) Web Worker: </strong>Use a Web Worker to load third-party scripts and offload their execution from the main thread. It prevents UI blocking and improving responsiveness. This is especially useful for heavy analytics or tracking scripts like <strong>Google Tag Manager</strong> and <strong>MS Clarity</strong>.</p><h4>5. Performance Monitoring</h4><p>Performance monitoring can be divided into two types of metrics: Browser-Centric and User-Centric (User Perception).</p><p><strong>Browser-Centric Metrics:</strong> These focus on the technical aspects of page loading and rendering.</p><p><strong>a) Time to First Byte (TTFB):</strong> The time it takes for the browser to receive the first byte of data from the server after making a request.</p><p><strong>b) Network Request and Load Time:</strong> The time it takes for the network to send a request and receive a response, including all assets required to load the page.</p><p><strong>c) DNS Resolution / DNS Lookup:</strong> The time it takes for the browser to translate the domain name into an IP address. You can implement caching to improve this.</p><p><strong>d) Connection Time:</strong> The time it takes to establish a connection between the client and the server.</p><p><strong>e) DOM Content Loaded:</strong> The time when the HTML is fully loaded and parsed, excluding images and stylesheets.</p><p><strong>f) Page Load:</strong> The total time it takes for the page to load completely, including all assets like images, scripts, and styles.</p><p><strong>User-Centric Metrics (Mainly Web Vitals):</strong> These focus on how users perceive the performance of a page.</p><p><strong>a) First Contentful Paint (FCP):</strong> Measures the time from when the page starts loading to when any part of the page’s content (like text or images) is rendered on the screen.</p><p><strong>b) Largest Contentful Paint (LCP):</strong> Measures the time from when the page starts loading to when the largest content element (text block or image) is rendered.</p><p><strong>c) Interaction to Next Paint (INP):</strong> Measures the responsiveness of the page by tracking the latency of interactions (tap, click, or keyboard action). It records the worst interaction latency as a representative value of the page’s overall responsiveness.</p><p><strong>d) Total Blocking Time (TBT):</strong> Measures the total time between FCP and Time to Interactive (TTI) where the main thread was blocked, preventing the page from responding to user input.</p><p><strong>e) Cumulative Layout Shift (CLS):</strong> Measures the total score of unexpected layout shifts that occur while the page is loading, affecting visual stability.</p><p><strong>f) Time to First Byte (TTFB):</strong> Measures how long it takes for the network to respond to a user request with the first byte of the resource.</p><p>To measure performance, you can use various tools such as <strong>PageSpeed Insights</strong>, <strong>Chrome DevTools</strong> (Network and Performance tabs), <strong>Lighthouse</strong>, <strong>Microsoft Clarity</strong>, etc</p><h3>Network Optimization</h3><p>Below are the various network optimization techniques we will cover:</p><ol><li>Minimize the HTTP Request</li><li>Loading of JS: async / defer</li><li>Avoid Redirection</li><li>Resource Hinting</li><li>Fetch Priority</li><li>Early Hints</li><li>HTTP upgrade methods (http 1.1 VS http2 VS http3)</li><li>Compression (brotli / gzip)</li><li>Optimizing third-party Scripts like Google Tag Manager, Analytics, MS Clarity (Already discussed in the Client Side Optimization Section)</li><li>HTTP caching: Cache Control</li><li>Caching using a Service Worker</li></ol><h4>Optimize the Network Request</h4><p>When optimizing for faster page loads, optimizing network requests can greatly improve site speed. Here are some key challenges and solutions:</p><h4>Challenges:</h4><ol><li><strong>Connection Overhead</strong>: Each new connection requires setup time, including steps like TCP handshakes and SSL Handshake.</li><li><strong>Browser Limitations</strong>: Browsers limit the number of parallel requests per domain (usually 6–10), meaning too many requests can block loading.</li></ol><h4>Solutions:</h4><p>1. <strong>Images: </strong>Compress images. Use images like Base64, and SVG for icons and small images. This reduces extra requests and allows images to load directly within HTML or CSS.</p><p>2. <strong>Minimize (Reduce) external requests: </strong>Limit the number of external libraries and services you use. Whenever possible, bundle dependencies to avoid multiple network calls.</p><p>3. <strong>Load scripts asynchronously: </strong>Use async or defer attributes for scripts to prevent them from blocking page rendering.</p><p>4. <strong>Avoid long running JavaScript: </strong>Ensure your code doesn’t block the main thread with tasks that take longer time to execute, which can cause pages to feel unresponsive. Load them in the background using a <strong>service worker</strong> if possible.</p><p>5.<strong> Avoid Redirection: </strong>Reduce unnecessary redirects like going from HTTP to HTTPS (http://www.flipkart.com/ to <a href="https://www.flipkart.com/).">https://www.flipkart.com/).</a> Instead, preload HTTPS in browsers using HSTS preload to avoid redirect delays.</p><p>6.<strong> Resource Hinting: </strong>Resource hints are directives that help browsers pre-optimize resource loading. Use them as follows:</p><p><strong>Preconnect:</strong> Pre-establish early connections to important domains (e.g., CDNs) to reduce latency. Avoid handshake.</p><pre>&lt;link rel=&quot;preconnect&quot; href=&quot;https://cdn.example.com&quot; crossorigin /&gt;</pre><p><strong>DNS Prefetch:</strong> Resolve DNS for domains that will be accessed later. Avoid using DNS prefetch if preconnect is already in place, as preconnect also handles DNS resolution.</p><pre>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;https://cdn.example.com&quot; /&gt;</pre><p><strong>Preload:</strong> Preload assets critical to page rendering, like fonts or hero images, for improved performance on initial load.</p><pre>&lt;link <br> rel=&quot;preload&quot; <br> href=&quot;https:images.flower.avif&quot; <br> as=&quot;image&quot; <br> type=&quot;image/avif&quot; <br> crossorigin  <br> /&gt;<br> &lt;link <br> rel=&quot;preload&quot; <br> href=&quot;https://example.com/fonts/font.woff2&quot; <br> as=&quot;font&quot; <br> type=&quot;font/woff2&quot; <br> crossorigin <br>/&gt;</pre><p><strong>Prefetch:</strong> Needed in the near future navigation like prefetch of image or a js chunk.</p><pre>&lt;link rel=&quot;prefetch&quot; href=&quot;https://example.com/scripts/next-page.js&quot; /&gt;</pre><p>7. <strong>Fetch Priority / Resource hinting priority: </strong>Use the <strong>fetchpriority</strong> attribute to prioritize image loading. Set it to high for above-the-fold content and low for less important images.</p><pre>&lt;img src=&quot;hero.jpg&quot; fetchpriority=&quot;high&quot; alt=&quot;Hero Image&quot; /&gt;<br>&lt;img src=&quot;footer-logo.jpg&quot; fetchpriority=&quot;low&quot; alt=&quot;Footer Logo&quot; /&gt;</pre><p>8.<strong> Early Hint: </strong>Early Hints (HTTP status code 103) allow servers to send hints about critical resources to browsers before the main response, optimizing load times. This allows a browser to preconnect to sites or start preloading resources even before the server has prepared and sent a final response. Preloaded resources indicated by early hints are fetched by the client as soon as the hints are received.</p><p><strong>Example HTTP Response with Early Hints:</strong> Servers can send a preliminary 103 response with hints about critical resources like stylesheets or scripts.</p><pre>HTTP/1.1 103 Early Hints<br>Link: &lt;/main.abcd100.css&gt;; rel=preload; as=style<br>Link: &lt;/script.abcd100.js&gt;; rel=preload; as=script<br><br>HTTP/1.1 200 OK<br>Content-Type: text/html<br><br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;/main.abcd105.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;script src=&quot;/script.abcd105.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote>Note: Early Hints require server support, such as HTTP/2 or HTTP/3, and are typically implemented at the CDN or reverse proxy level.</blockquote><p>8. <strong>HTTP Upgrade (http 1.1 VS http2 VS http3):</strong></p><ul><li><strong>Speed</strong>: HTTP/3 &gt; HTTP/2 &gt; HTTP/1.1</li><li><strong>Security</strong>: HTTP/3 &gt; HTTP/2 &gt; HTTP/1.1</li><li><strong>Compatibility</strong>: HTTP/1.1 &gt; HTTP/2 &gt; HTTP/3</li><li><strong>Ease of Debugging</strong>: HTTP/1.1 &gt; HTTP/2 &gt; HTTP/3</li></ul><p>9. <strong>Compression (brotli / gzip):</strong></p><ul><li><strong>GZIP:</strong> A widely-used text compression algorithm since 1992. It reduces file size to speed up web page load times and is supported by nearly all browsers and servers.</li><li><strong>Brotli:</strong> A newer compression algorithm (2013) with better compression rates than GZIP, reducing file sizes further while maintaining speed.</li></ul><p><strong>Benefits of GZIP and Brotli</strong></p><ul><li><strong>Smaller Files:</strong> Reduces text file sizes (e.g., HTML, CSS, JS) to save bandwidth.</li><li><strong>Faster Load Times:</strong> Smaller files transfer faster, improving page load speed and user experience.</li><li><strong>Compatibility:</strong> Brotli achieves up to 70% compression; GZIP achieves around 65%.</li><li><strong>Fallback Options:</strong> Brotli is supported by 96% of browsers; GZIP acts as a fallback for older browsers like IE11.</li></ul><p>10. <strong>HTTP caching: </strong>HTTP caching helps reduce page load times by storing copies of resources (e.g., HTML, CSS, JavaScript) locally in a browser or at intermediary servers (e.g., CDNs). This avoids redundant requests and improves performance.</p><p><strong>Types of Caching</strong></p><ol><li><strong>Browser Cache</strong></li></ol><ul><li>Stores resources locally in the user’s browser.</li><li>Reduces load time for repeat visits by serving cached files.</li></ul><p>2.<strong> CDN Cache</strong></p><ul><li>Distributed cache used by CDNs to store resources closer to users.</li><li>Reduces latency by avoiding direct requests to the origin server.</li></ul><p>11.<strong> Service worker caching: </strong>A service worker intercepts network-type HTTP requests and uses a caching strategy to determine what resources should be returned to the browser. The service worker cache and the HTTP cache serve the same general purpose, but the service worker cache offers more caching capabilities, such as fine-grained control over exactly what is cached and how caching is done.</p><p><strong>Benefits</strong></p><ol><li><strong>Offline Access</strong>: Serve cached resources when offline.</li><li><strong>Faster Load Times</strong>: Cache static assets and serve them directly.</li><li><strong>Customizable Caching</strong>: Define cache policies for different resources.</li></ol><pre>const CACHE_NAME = &#39;my-app-cache-v1&#39;;<br>const FILES_TO_CACHE = [<br>  &#39;/&#39;,<br>  &#39;/index.html&#39;,<br>  &#39;/styles.css&#39;,<br>  &#39;/script.js&#39;,<br>  &#39;/logo.png&#39;,<br>];<br><br>// Install event: Cache files<br>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      return cache.addAll(FILES_TO_CACHE);<br>    })<br>  );<br>});<br><br>// Fetch event: Serve from cache or network<br>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  event.respondWith(<br>    caches.match(event.request).then((response) =&gt; {<br>      return response || fetch(event.request);<br>    })<br>  );<br>});<br><br>// Activate event: Clean up old caches<br>self.addEventListener(&#39;activate&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.keys().then((cacheNames) =&gt;<br>      Promise.all(<br>        cacheNames<br>          .filter((name) =&gt; name !== CACHE_NAME)<br>          .map((name) =&gt; caches.delete(name))<br>      )<br>    )<br>  );<br>});</pre><h3>Build Optimization</h3><h4>Bundler</h4><p>A bundler is a tool that processes and optimizes frontend code, transforming it into a browser-compatible format. It takes various inputs like TypeScript, SCSS, and modern JavaScript and outputs an optimized bundle with features like transpilation, minification, and fallback support for older browsers.</p><h4>Some different types of bundlers:</h4><ol><li>Esbuild</li><li>Webpack</li><li>Vite</li><li>Rollup</li><li>Parcel</li></ol><h4>Build Optimization can be generally categorized into ways:</h4><h4>1. User Experience:</h4><p>User Experience optimizations done during build times:</p><ul><li>Code Splitting</li><li>Tree Shaking</li><li>Minification</li><li>Cross Browser Compatibility</li><li>Code Obfuscation: Obfuscation means to make something difficult to understand. This is often done to protect intellectual property or make it harder for attackers to reverse-engineer the code. It also helps in inspecting and rewriting the code to reduce its size.</li></ul><pre>// Programmer Code<br>function getUserData() {<br>    return &quot;Sensitive Data&quot;;<br>}<br>console.log(getUserData());<br><br>// After Code Obfuscation<br>function a() {<br>    return &quot;Sensitive Data&quot;;<br>}<br>console.log(a());<br><br>// Programmer Code<br>function greet(name) {<br>    console.log(`Hello, ${name}!`);<br>}<br><br>greet(&quot;Alice&quot;);<br><br>// After Code Obfuscation<br>var _0x1234 = [&quot;log&quot;, &quot;Hello, &quot;, &quot;!&quot;];<br>(function (_0x5678, _0x9abc) {<br>    var _0xdef0 = function (_0x1357) {<br>        while (--_0x1357) {<br>            _0x5678[&quot;push&quot;](_0x5678[&quot;shift&quot;]());<br>        }<br>    };<br>    _0xdef0(++_0x9abc);<br>})(_0x1234, 0x2);<br><br>var _0x2345 = function (_0x5678, _0x9abc) {<br>    _0x5678 = _0x5678 - 0x0;<br>    var _0xdef0 = _0x1234[_0x5678];<br>    return _0xdef0;<br>};<br><br>function greet(_0x6789) {<br>    console[_0x2345(&quot;0x0&quot;)](_0x2345(&quot;0x1&quot;) + _0x6789 + _0x2345(&quot;0x2&quot;));<br>}<br><br>greet(&quot;Alice&quot;);</pre><ul><li>Pruning and Optimizing CSS</li><li>Compression: Reducing the file size of JS, CSS, etc. It can be done using Brotli or GZIP. It needs to be enabled/applied during the bundling phase and then can be shipped via the network layer.</li><li>Optimizing Images and assets</li><li>Remove Source Maps in Production. Keep it only in the Development mode.</li><li>Profiling and Analyzing bundles</li><li>Pre-rendering (SSG)</li><li>Cache using asset hashing: Asset hashing is a technique where filenames of bundled assets (JS, CSS, images, etc.) include a unique hash (based on file content). This ensures that browsers only fetch new versions when the file changes, preventing unnecessary re-downloads and improving caching efficiency. When a file changes, its hash changes, and the browser downloads the new version. If the file stays the same, it uses the cached version.</li></ul><blockquote>Example: A file named <strong>app.js</strong> → after hashing → <strong>app.a1b2c3.j</strong>s</blockquote><blockquote>Next time you modify <strong>app.js</strong>, a new hashed file gets generated: <strong>app.d4e5f6.js</strong></blockquote><ul><li>Vendor Chunk Splitting: It is a bundling optimization technique where third-party dependencies (like Carousel Package, Lodash, or Axios) are separated from your application’s code into a dedicated “vendor” bundle. This helps improve caching, load times, and overall performance. With vendor chunk splitting, a third-party dependency used in a particular route will be downloaded only when that route is loaded. Without it, the dependency will be downloaded on all pages.</li></ul><h4>2. Developer Experience:</h4><ul><li>Faster Builds</li><li>Parallelization: Parallelization in bundling refers to the process of splitting tasks across multiple CPU cores or threads to speed up the build process. Instead of processing files sequentially, modern bundlers utilize parallel processing to optimize performance. Most bundlers, such as Webpack, Vite, Rollup, Parcel, and esbuild, leverage worker threads or multiple processes to speed up bundling.</li><li>Cache Management: It is a mechanism that stores intermediate build results to avoid redundant computations and speed up <strong>subsequent builds</strong>. Instead of rebuilding everything from scratch, bundlers like Webpack reuse previously compiled modules and assets, significantly improving performance.</li><li>Incremental Compilation: Incremental Compilation is a build optimization technique where only the changed files are recompiled instead of rebuilding everything from scratch. This significantly speeds up the development and build process, especially for large projects.</li><li>HMR (Hot Module Replacement): HMR is a feature in modern bundlers that updates modules in real-time without requiring a full page reload. This drastically improves development speed and experience by keeping the state intact while applying code changes.</li><li>Monorepos with tools like Lerna or Nx: A monorepo (monolithic repository) is a single Git repository that stores multiple related projects, often sharing dependencies and configurations. Tools like Lerna and Nx help manage monorepos efficiently, improving code sharing, dependency management, and scalability.</li></ul><p><strong>Thank you for reading this far! I hope you now have a clear understanding of frontend optimization techniques and strategies. This blog was designed as a handbook or checklist that you can revisit whenever needed.</strong></p><p><strong>Performance optimization is an ongoing process, and there’s always more to explore — so keep learning, experimenting, and refining your approach!</strong></p><h3>If you want more web development content then follow me on <a href="https://rajeshi.medium.com/">Medium </a>and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <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=d86ca9bdb624" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/frontend-performance-handbook-best-practices-and-strategies-d86ca9bdb624">Frontend Performance Handbook — Best Practices and Strategies</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[Understanding SSH: A Practical Developer’s Guide]]></title>
            <link>https://blog.devgenius.io/understanding-ssh-a-practical-developers-guide-c85bcd31447a?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85bcd31447a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ssh-keys]]></category>
            <category><![CDATA[ssh-tunnel]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 14:20:58 GMT</pubDate>
            <atom:updated>2023-02-02T21:07:14.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdRWS0-7BmvZ8vTL4rscnQ.png" /></figure><p>If you are a developer then I am sure you heard about SSH. No matter how awesome your web app is, if you want people to use it then you need to put it online. And if you want your deployment process to be safe then SSH is going to be your best buddy.</p><p>In this blog, We will cover the basics of SSH and different encryption technologies. We will also see some commands so that you can safely deploy your app online.</p><h3>What is SSH (Secure Shell or Secure Socket Shell)?</h3><p>SSH is a protocol that allows users to access the remote server and modify them. It is a secure way to establish a connection with the remote server. It uses cryptographic techniques so that all the communication you make with the remote server is encrypted and safe. It is a secure alternative to Telnet.</p><p>With SSH, developers can access the remote server from their terminal and securely deploy their app online.</p><h3>How to start with SSH?</h3><p>SSH can be used directly from the terminal of your Windows, Linux, and Mac. But on older versions of windows, you need to use an SSH client like putty.</p><blockquote>SSH Syntax</blockquote><pre>ssh {user}@{host}</pre><blockquote>SSH Command</blockquote><pre>ssh root@137.44.309.64 or ssh root@xyz.com</pre><p>In the command <strong>ssh </strong>keyword instructs the computer to open an SSH connection, the <strong>user </strong>represents the account you want to access, and the <strong>host </strong>refers to the computer you want to access. The host can be an IP address or domain name.</p><h3>Different Encryption Techniques In SSH</h3><p>There are three different encryption techniques used by SSH:</p><ol><li><strong>Symmetrical encryption: </strong>In Symmetric encryption, one secret key is used for both the encryption and decryption of a message by both the client and the host. The exchange of the secret key is done so that it can be used in the decryption process. Anyone possessing the key can decrypt the message being transferred. It is often called shared key or shared secret encryption.</li><li><strong>Asymmetric Encryption:</strong> Asymmetric encryption uses public and private keys. The public key is used for encryption, and the private key is used for decryption. A public key can be used by any individual to encrypt a message and can only be decrypted by the recipient who possesses their particular private key, and vice versa.</li><li><strong>Hashing:</strong> With Hashing, a unique hash value of a fixed length is generated for each input which cannot be exploited. We can easily generate a cryptographic hash from a given input, but we cannot generate the input from the hash. The recipient takes the input from the sender and applies the same hashing which was applied by the sender and compares the hashed value to verify whether they possess the correct input.</li></ol><h3>Some Basic SSH Commands</h3><p>Below is the list of some basic SSH commands:</p><ol><li><strong>ls:</strong> shows the list of all files and directories.</li></ol><pre>ls</pre><p><strong>2. cd:</strong> change the directory.</p><pre>cd directory_name</pre><p><strong>3. mkdir:</strong> create a directory.</p><pre>mkdir folder_name</pre><p><strong>4. rm:</strong> removes a file or directory.</p><pre>rm file_name.txt</pre><p><strong>5. pwd:</strong> gives the path of your present working directory.</p><pre>pwd<br><br>// Output<br>user/project/index.html</pre><p><strong>Thank you for reading this far. I hope you understood SSH and its importance.</strong></p><h3>If you want more web development content then follow me on <a href="https://rajeshi.medium.com/">Medium </a>and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85bcd31447a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-ssh-a-practical-developers-guide-c85bcd31447a">Understanding SSH: A Practical Developer’s Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Modern frontend development trends you need to learn]]></title>
            <link>https://javascript.plainenglish.io/5-modern-frontend-development-trends-you-need-to-learn-8be82b33d591?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be82b33d591</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 10:27:21 GMT</pubDate>
            <atom:updated>2023-01-17T02:54:03.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5pBhWH9OuClnpxVV01SDg.png" /></figure><p>Frontend development is evolving and getting more complex every single day. With the evolving frontend trends and ecosystem, frontend developers need to focus on multiple aspects from keeping up with the latest UI/UX to improving the performance of web applications.</p><p>And to deal with these challenges new technologies, frameworks, etc are being introduced regularly. And so the developers have to keep up with the latest trends. Here’s an overview of top frontend development trends you might need to catch up on if you haven’t already.</p><h3>Front-End Development Trends</h3><h4>Accessibility</h4><p><a href="https://javascript.plainenglish.io/everything-you-should-know-about-web-accessibility-2d743268506c">Accessibility </a>means making your websites usable by as many people as possible. We tend to think that it is all about making websites usable for people with disability, but it is partially true. The accessibility practice also benefits other groups of users such as those using mobile devices, or those with slow network connections.</p><p>Read the complete accessibility blog <a href="https://javascript.plainenglish.io/everything-you-should-know-about-web-accessibility-2d743268506c"><strong>here</strong></a></p><h4>Motion UI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDKM_hSqPzpwxja2_J1anA.gif" /></figure><p>Motion UI is a modern frontend development style that makes websites and apps more interactive and engaging. By adding movement and animation to UI elements it tells stories and evokes emotions in users, which helps to increase engagement. It is a simple and effective way to grab users’ attention. It makes your website look stunning and visually appealing.</p><h4>Performance optimization</h4><p>Frontend performance optimization is not only a trend but also a very important part of frontend development. No user is willing to wait for several minutes till the page loads completely. With the evolving frontend ecosystem performance is that one thing you can’t afford to miss out on. Some of the major things you need to focus on are state management, compressing your images, bundling and minifying HTML, CSS, and JAVASCRIPT files, lazy loading, etc</p><h4>Mobile First Design</h4><p>A mobile-first approach encouraged developers to begin the development process for the smallest devices first and then add more functionalities for bigger screen sizes. Mobile users continue to grow with a leading market share of 60.43% as compared to desktop users. Popular CSS framework like <a href="https://tailwindcss.com/">tailwind </a>also follows a mobile-first approach.</p><h4>Server Side Rendering</h4><p>Server-side rendering (SSR) generates the HTML on the server and sends it directly to the client. This allows the website to load faster and ensures that search engines can properly index the content. It helps to improve the performance and SEO of web applications. One of the main benefits of SSR is that it can improve the initial load time of a website.</p><p>Another benefit of SSR is that it sends the initial HTML to the client including the content, making it fully indexable by search engines. Hence, it improves the SEO of a website.</p><p>There are a few libraries and frameworks that can be used to implement SSR in a web application such as Next.js, Nuxt.js, etc.</p><p><strong>Thank you for reading this far. I hope you are going to follow these trends or learn more about them if you haven’t already.</strong></p><h3>If you want to learn web development then follow me on <a href="https://rajeshi.medium.com/">Medium </a>and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><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>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be82b33d591" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-modern-frontend-development-trends-you-need-to-learn-8be82b33d591">5 Modern frontend development trends you need to learn</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[Learn web development and get a high paying job]]></title>
            <link>https://blog.devgenius.io/learn-web-development-and-get-a-high-paying-job-f126558a4abb?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f126558a4abb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 10:11:20 GMT</pubDate>
            <atom:updated>2023-01-07T10:47:47.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWUTLqy0eZXwVxn8ITmKsg.png" /></figure><p>Web Development Jobs are on the rise and will continue to be in high demand. Being an expert web developer is going to take you far ahead in your career. Anyone can learn the basics concepts but only a few works hard, practice every day and become an expert. If you are good at web development then you are going to get plenty of opportunities and enjoy a high-growth career.</p><p>In this blog, I am going to give you a complete path to learning Web Development, Resume building, Interview Tips, and how to land a high-paying job.</p><h3>The Fundamentals</h3><p>The website or web app is divided into two parts i.e., frontend and backend. Let us learn what is frontend and backend in brief.</p><p><strong>Frontend: </strong>The frontend is the part of the website users can see and interact with such as texts, images, videos, like or share buttons, etc. Basically, when you open a website whatever you see there is the front end. The frontend is built using HTML, CSS, and JAVASCRIPT.</p><p><strong>Backend:</strong> The backend is the part of the website where users&#39; data or information are stored and processed. The frontend makes the request to the backend and displays that information. For example, all your photos of Instagram are stored in the backend. And when you open Instagram at that moment Instagram frontend requests its backend and you get to see all those amazing photos of yours. The backend is built using Nodejs, MongoDB, Php, MySQL, etc.</p><h3>The Frontend Roadmap</h3><p>Let us go through the roadmap of learning frontend development. In order to build the frontend of a website or web app we use <a href="https://www.youtube.com/watch?v=V3HyMWes8Gc">HTML</a>, <a href="https://www.youtube.com/watch?v=FcIqM7MhEow">CSS</a>, and JAVASCRIPT.</p><h4>HTML</h4><p>HTML is also known as Hypertext Markup Language is the core of a website. It is the building block of any website. All the text, images, buttons, etc whatever you see is created using HTML.</p><h4>CSS</h4><p>Cascading style sheets in short CSS is used to add styling and make your website look beautiful. You might have seen text of different colors, and images of different shapes and sizes while visiting some websites all that is done using CSS.</p><h4>JAVASCRIPT</h4><p>JavaScript is a language that adds functionality to your website. Consider JavaScript as the brain of the website. For example, whenever you like a post on social media the color of the like button changes, and the like count is increased all that is achieved using JavaScript.</p><h4>REACT</h4><p>Building a large-scale website using JavaScript can be inefficient because it is going to make your code more complex and hard to manage. So some awesome engineers at Meta created a new technology on top of JavaScript that helps you to write JavaScript in a better way so that your code becomes less complex and easy to manage. And hence we call react a JavaScript library. React is in high demand and if you learn it well then you will be getting many job opportunities that pay you well.</p><p>React is not a new programming language. It helps you write JavaScript in a better way. React makes your job easy as a developer and saves your time from writing long JavaScript code. With React you can achieve it with few lines.</p><h3>The Backend Roadmap</h3><p>Let us go through the roadmap of learning backend development. In order to build the backend of a website or web app we use NodeJs, MongoDB, etc. There are other tech stacks like PHP and MySQL but we will not focus on those because for the backend NodeJs and MongoDB are in high demand.</p><h4>NodeJs</h4><p>Node.js is an open-source and cross-platform runtime environment using which you write JavaScript code to build the backend of your website. Yes, the same JavaScript which we use in building frontend.</p><h4>MongoDB</h4><p>MongoDB is a document database where all user information is stored. It is also known as a NoSQL database because the storage and retrieval of data in MongoDB are not in the form of tables.</p><h3>The different job roles</h3><p>In Web Development you will be having three job roles: Frontend, Backend, and FullStack (one who knows both frontend and backend). You can try learning both frontend and backend then later apply for the role that suits you best.</p><h3>Resume Building</h3><p>Once you learn the skills it is time to build a good resume and apply for the role you desire. Read the below points to make your resume stand out from the crowd.</p><ol><li>Add only what is required in the job role. Don’t add unnecessary things like your hobby, etc.</li><li>Your resume should be one page not more than that. Recruiters don’t like to waste their time reading a 2–3 pages resume.</li><li>Make sure to add the projects you build respective to the role you are applying for.</li><li>Add the relevant skills which fit the job role.</li><li>Add a valid phone number and email so that the recruiter can reach you.</li><li>Proofread your resume yourself or send it to your friend and remove all those typos before applying</li></ol><h3>Interview Round</h3><p>Once your resume is selected you will get a call for an Interview. Depending on the company you will be having multiple Interview rounds from 3 — 5 rounds. The order of the Interview rounds is given below.</p><ol><li><strong>Domain round: </strong>Here you will be asked different questions based on the role you applied for.</li><li><strong>Problem solving: </strong>In this round, you will be asked some of the Data structure questions. Complexity is going to vary from company to company and also it depends on the level of role you are applying for.</li><li><strong>HR Round: </strong>This is a culture fit and background checking round where you will be asked some of the questions like Tell me about yourself, Five-year goals, Why should we hire you, etc.</li></ol><p>So these are the main three rounds you will be going through in every single company. But there can be more rounds of Interviews. It can go up to 5 rounds depending on the company.</p><h3>Job Hunting</h3><p>Once you have learned the skills well, build some good projects, and your resume is ready. It is time for job hunting. Below is the list of websites where you can apply for jobs:</p><ol><li><strong>LinkedIn: </strong><a href="https://www.linkedin.com/">https://www.linkedin.com/</a></li><li><strong>Wellfound (formerly AngelList):</strong> <a href="https://angel.co/">https://angel.co/</a></li><li><strong>JustRemote:</strong> <a href="https://justremote.co/">https://justremote.co/</a></li><li><strong>Hired:</strong> <a href="https://hired.com/">https://hired.com/</a></li><li><strong>Arc:</strong> <a href="https://arc.dev/">https://arc.dev/</a></li><li><strong>FlexJobs:</strong> <a href="https://www.flexjobs.com/">https://www.flexjobs.com/</a></li><li><strong>Working Nomads:</strong> <a href="https://www.workingnomads.com/jobs">https://www.workingnomads.com/jobs</a></li></ol><p><strong>Thank you for reading this far. I hope now you got a complete understanding of how to learn web development and get a job.</strong></p><h3>If you want to learn web development then follow me on <a href="https://rajeshi.medium.com/">Medium </a>and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h4><strong>Any doubt? reach me on </strong><a href="https://twitter.com/izrajesh"><strong>Twitter</strong></a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f126558a4abb" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/learn-web-development-and-get-a-high-paying-job-f126558a4abb">Learn web development and get a high paying job</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useState hook Mistakes You Must Avoid!]]></title>
            <link>https://javascript.plainenglish.io/react-usestate-hook-mistakes-you-must-avoid-fde757ca52f5?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde757ca52f5</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[usestate-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 10:34:05 GMT</pubDate>
            <atom:updated>2022-12-19T12:39:49.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-Ok0PvNXZ6pvAHbRHXLUg.png" /></figure><p>In this blog, We will discuss the top 5 common useState hook mistakes that React developer makes. We will see all the common mistakes step by step and learn how to fix them with examples.</p><h3>1. Depending on the API response to fill the state</h3><p>I have seen many React developers define the useState hook without initializing it properly and later add the data with an API response. This is going to give you an error when you try to access the state data before the component renders because getting an API response is going to take some time.</p><blockquote>Let us see an example below</blockquote><p><strong>Initialize Component</strong></p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const Initialize = () =&gt; {<br>    const [product, setProduct] = useState();<br><br>    useEffect(() =&gt; {<br>        // Consider this as an API response<br>        const apiResponse = {<br>            name: &quot;T-Shirt&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A super coll T-Shirt for you&quot;<br>        }<br>        setProduct(apiResponse);<br>    }, [])<br>    return (<br>        &lt;div&gt;<br>            &lt;h3&gt;{product.name}&lt;/h3&gt;<br>            &lt;p&gt;{product.price}&lt;/p&gt;<br>            &lt;p&gt;{product.description}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default Initialize;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*AkDBsi2IaAVycxWFX3UQzw.png" /><figcaption>useState hook gives cannot read properties of undefined error</figcaption></figure><p>We are accessing the name property from the product state which is not there in the state. It gets added later once the API call is successful. So during the rendering of the component the product state is undefined. One good way to fix this error is to initialize the state.</p><p><strong>Initializing the state in Initialize Component</strong></p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const Initialize = () =&gt; {<br>    const [product, setProduct] = useState({<br>        name: &quot;&quot;,<br>        price: &quot;&quot;,<br>        description: &quot;&quot;<br>    });<br><br>    useEffect(() =&gt; {<br>        // Consider this as an API response<br>        const apiResponse = {<br>            name: &quot;T-Shirt&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A super coll T-Shirt for you&quot;<br>        }<br>        setProduct(apiResponse);<br>    }, [])<br>    return (<br>        &lt;div&gt;<br>            &lt;h3&gt;{product.name}&lt;/h3&gt;<br>            &lt;p&gt;{product.price}&lt;/p&gt;<br>            &lt;p&gt;{product.description}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default Initialize;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*QVgnkwI2gi-7-YC49Lr61w.png" /><figcaption>No Error in the console</figcaption></figure><p>After initializing the state, the error is gone from the console and we can clearly see the data on the web page.</p><h3>2. Creating a state change method for each input element</h3><p>Let&#39;s just say you have a form component where multiple input elements are present. Now you need to get the value from those input elements and update your component state. In this case, some Junior developers create a unique handle change function for each input element which is not a good way to handle the form data.</p><blockquote>Let us see an example below</blockquote><p><strong>UpdateState component</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>function UpdateState() {<br>  const [formData, setFormData] = useState({name: &#39;&#39;, email: &#39;&#39;, password: &#39;&#39;});<br><br>  const handleName = event =&gt; {<br>    setFormData({...formData, name: event.target.value})<br>  }<br><br>  const handleEmail = event =&gt; {<br>    setFormData({...formData, email: event.target.value})<br>  }<br><br>  const handlePassword = event =&gt; {<br>    setFormData({...formData, password: event.target.value})<br>  }<br><br>  const handleSubmit = () =&gt; {<br>    console.log(formData);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;name&quot;&gt;Enter your Name&lt;/label&gt;<br>        &lt;input <br>         type=&quot;text&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your name&quot; <br>         id=&quot;name&quot; <br>         onChange={handleName}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>        &lt;input <br>         type=&quot;email&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your email&quot; <br>         id=&quot;email&quot; <br>         onChange={handleEmail}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Enter your Password&lt;/label&gt;<br>        &lt;input <br>         type=&quot;password&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your password&quot; <br>         id=&quot;password&quot; <br>         onChange={handlePassword}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UpdateState;</pre><p>As I said this is not a good way to handle form data. We need to have just one single function which is going to receive the data from all the input fields and update the state. Let us look at the below code and see how can we do that.</p><p><strong>UpdateState component</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>function UpdateState() {<br>  const [formData, setFormData] = useState({name: &#39;&#39;, email: &#39;&#39;, password: &#39;&#39;});<br><br>  const handleChange = name =&gt; event =&gt; {<br>    setFormData({...formData, [name]: event.target.value})<br>  }<br><br>  const handleSubmit = () =&gt; {<br>    console.log(formData);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;name&quot;&gt;Enter your Name&lt;/label&gt;<br>        &lt;input <br>         type=&quot;text&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your name&quot; <br>         id=&quot;name&quot; <br>         onChange={handleChange(&quot;name&quot;)}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>        &lt;input <br>         type=&quot;email&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your email&quot; <br>         id=&quot;email&quot; <br>         onChange={handleChange(&quot;email&quot;)}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Enter your Password&lt;/label&gt;<br>        &lt;input <br>         type=&quot;password&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your password&quot; <br>         id=&quot;password&quot; <br>         onChange={handleChange(&quot;password&quot;)}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UpdateState;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDsc6S50S658XLaBuy62ug.png" /><figcaption>logging out the form data after clicking submit button</figcaption></figure><h3>3. Rendering the component while updating input data</h3><p>You can see in the above example I have used the onChange method in every input element which is going to update the state. And we know once the state is updated the component re-renders to reflect new changes. The problem with this is every time we input a character in an input field our component re-renders. This unnecessary re-rendering of components can be avoided using the <a href="https://javascript.plainenglish.io/what-is-useref-hook-forwardref-in-react-a-complete-explanation-8f55496875ca"><strong>useRef </strong></a>hook. If you want a detailed explanation about the useRef hook and forwardRef then <a href="https://javascript.plainenglish.io/what-is-useref-hook-forwardref-in-react-a-complete-explanation-8f55496875ca"><strong>Click Here</strong></a>.</p><blockquote>Let us see an example below</blockquote><p><strong>UseRefImplement component</strong></p><pre>import React, { useRef } from &#39;react&#39;;<br><br>const UseRefImplement = () =&gt; {<br>    const formField = useRef(null);<br><br>    const handleSubmit = () =&gt; {<br>        console.log(formField.current[&#39;name&#39;].value);<br>        console.log(formField.current[&#39;email&#39;].value);<br>        console.log(formField.current[&#39;password&#39;].value);<br>    }<br>    return (<br>    &lt;div&gt;<br>      &lt;form ref={formField}&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;name&quot;&gt;Enter your Name&lt;/label&gt;<br>        &lt;input <br>         type=&quot;text&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your name&quot; <br>         id=&quot;name&quot; <br>         name=&quot;name&quot;<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>        &lt;input <br>         type=&quot;email&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your email&quot; <br>         id=&quot;email&quot; <br>         name=&quot;email&quot;<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Enter your Password&lt;/label&gt;<br>        &lt;input <br>         type=&quot;password&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your password&quot; <br>         id=&quot;password&quot; <br>         name=&quot;password&quot;<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;/form&gt;<br><br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UseRefImplement;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*rvUFNoM8wMuwTXnm05s8Bg.png" /><figcaption>logging out the form data after clicking submit button</figcaption></figure><h3>4. Updating state with the async method</h3><p>In this case, let us directly look at the example first.</p><p><strong>AsyncMethod component</strong></p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const AsyncMethod = () =&gt; {<br>    const [count, setCount] = useState(0);<br><br>    const increment = () =&gt; {<br>        console.log(&quot;state updated&quot;);<br>        setCount(count+1);<br>    }<br><br>    const asyncIncrement = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setCount(count+1)<br>            console.log(&quot;Async state updated&quot;);<br>        }, 3000);<br>    }<br><br>    useEffect(() =&gt; {<br>        console.log(count);<br>    }, [count]);<br><br>    return (<br>        &lt;div className=&quot;async&quot;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;    <br>            &lt;div className=&quot;button-group&quot;&gt;<br>                &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>                &lt;button onClick={asyncIncrement}&gt;Async Increment&lt;/button&gt;<br>            &lt;/div&gt;   <br>        &lt;/div&gt;<br>    );<br>};<br><br>export default AsyncMethod;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*SbDE0f9rzZ_mfrMw9NsMyQ.png" /><figcaption>state update and async state update</figcaption></figure><p>Look at the console carefully. I have increased the number count to 7 by updating the state and now out of nowhere, you see 4 with an async state update.</p><h4>What is wrong with the Async state update?</h4><p>Actually, I increased the number count to 3 by clicking on the Increment button, and then I clicked on the Async Increment button. But you know the async function has setTimeout in it to mimic the async update. Now in the meantime, I increased the number count to 7 by clicking on the Increment button. And by this time the async state update got triggered and now according to the async method current state count is 3 because that&#39;s the count when I clicked on the async Increment. And hence it updates the count to 4 instead of 8.</p><p>This problem can be solved if the async state update method has a track of the current state. And we can do that by passing the callback function to the set state method</p><p><strong>AsyncMethod component</strong></p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const AsyncMethod = () =&gt; {<br>    const [count, setCount] = useState(0);<br><br>    const increment = () =&gt; {<br>        console.log(&quot;state updated&quot;);<br>        setCount(count+1);<br>    }<br><br>    const asyncIncrement = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setCount(prevCount =&gt; prevCount + 1)<br>            console.log(&quot;Async state updated&quot;);<br>        }, 3000);<br>    }<br><br>    useEffect(() =&gt; {<br>        console.log(count);<br>    }, [count]);<br><br>    return (<br>        &lt;div className=&quot;async&quot;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;    <br>            &lt;div className=&quot;button-group&quot;&gt;<br>                &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>                &lt;button onClick={asyncIncrement}&gt;Async Increment&lt;/button&gt;<br>            &lt;/div&gt;   <br>        &lt;/div&gt;<br>    );<br>};<br><br>export default AsyncMethod;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*qH83Oc2Pklx_4D0NJD50WA.png" /><figcaption>state update and async state update</figcaption></figure><p>And now you can see the issue is fixed just by passing the callback function to the set state method which has a track of the latest state data.</p><h3>Updating the derived state</h3><p>One of the most common mistakes the junior React developer makes is when there are two states in the component and the second state is derived from the first state then while updating the state they create a bug unknowingly.</p><blockquote>Let us see an example below</blockquote><p><strong>DeriveState component</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>const DeriveState = () =&gt; {<br>    const [products, setProducts] = useState([<br>        {<br>            name: &quot;T-Shirt&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A super cool T-Shirt for coders&quot;,<br>            selectedColor: &quot;crimson&quot;,<br>            id: 146<br>        },<br>        {<br>            name: &quot;Shoes&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A great pair of shoes for your casual use&quot;,<br>            selectedColor: &quot;crimson&quot;,<br>            id: 790<br>        }<br>    ])<br><br>    const [cartProduct, setCartProduct] = useState();  <br><br>    const addToCart = (productId) =&gt; {<br>        const product = products.find(product =&gt; product.id === productId);<br>        setCartProduct(product);<br>    }<br><br>    const handleColor = (color, productId) =&gt; {<br>        setProducts(currentProducts =&gt; currentProducts.map(product =&gt; {<br>            if (product.id === productId) {<br>                return {...product, selectedColor: color}<br>            }<br>            return product<br>        }));<br>    }<br><br>    return (<br>        &lt;div className=&quot;cards&quot;&gt;<br>            {<br>                cartProduct ?<br>                &lt;div className=&quot;card-added&quot;&gt;<br>                {cartProduct.selectedColor} {cartProduct.name} is added to cart<br>                &lt;/div&gt; : null<br>            }<br>            {<br>                products.map(product =&gt; (<br>                    &lt;div key={product.id} className=&quot;card&quot;&gt;<br>                      &lt;h3&gt;{product.name}&lt;/h3&gt;<br>                      &lt;p&gt;{product.description}&lt;/p&gt;<br>                      &lt;p&gt;{product.price}&lt;/p&gt;<br>                      &lt;p className=&quot;quantity&quot;&gt;<br>                      &lt;button onClick={() =&gt; addToCart(product.id)} className=&quot;cart-btn&quot;&gt;<br>                      Add To Cart<br>                      &lt;/button&gt;                   <br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;crimson&quot;, product.id)} <br>                        className=&quot;select-color crimson&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;green&quot;, product.id)} <br>                        className=&quot;select-color green&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;violet&quot;, product.id)} <br>                        className=&quot;select-color violet&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;black&quot;, product.id)} <br>                        className=&quot;select-color black&quot;&gt;+&lt;/span&gt;<br>                      &lt;/p&gt;<br>                    &lt;/div&gt;<br>                ))<br>            }<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default DeriveState;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*MTjoijMFye_wLlFYsgtQHQ.png" /><figcaption>The UI of Derive state component</figcaption></figure><p>You might be thinking hey that’s great all the functionality works what is the issue with the above code? Well, let me tell you there is a bug. If you click on the color buttons and try to update the color then the newly selected color doesn’t get reflected because here we have two different states and we are updating the only original one. The derive state is not updated.</p><p>In order to fix this bug we basically instead of storing the copy of the selected product in the derived state. We will store the id of the selected product. Look at the code below.</p><p><strong>DeriveState component</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>const DeriveState = () =&gt; {<br>    const [products, setProducts] = useState([<br>        {<br>            name: &quot;T-Shirt&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A super cool T-Shirt for coders&quot;,<br>            selectedColor: &quot;crimson&quot;,<br>            id: 146<br>        },<br>        {<br>            name: &quot;Shoes&quot;,<br>            price: &quot;$399&quot;,<br>            description: &quot;A great pair of shoes for your casual use&quot;,<br>            selectedColor: &quot;crimson&quot;,<br>            id: 790<br>        }<br>    ])<br><br>    const [cartProduct, setCartProduct] = useState();<br>    const [cartProductId, setCartProductId] = useState();<br>    const addedProductToCart = products.find(product =&gt; product.id === cartProductId);<br><br>    const addToCart = (productId) =&gt; {<br>        setCartProductId(productId);<br>    }<br><br>    const handleColor = (color, productId) =&gt; {<br>        setProducts(currentProducts =&gt; currentProducts.map(product =&gt; {<br>            if (product.id === productId) {<br>                return {...product, selectedColor: color}<br>            }<br>            return product<br>        }));<br>    }<br><br>    return (<br>        &lt;div className=&quot;cards&quot;&gt;<br>            {<br>                addedProductToCart ?<br>                &lt;div className=&quot;card-added&quot;&gt;<br>                {addedProductToCart.selectedColor} {addedProductToCart.name} is added to cart<br>                &lt;/div&gt; : null<br>            }<br>            {<br>                products.map(product =&gt; (<br>                    &lt;div key={product.id} className=&quot;card&quot;&gt;<br>                      &lt;h3&gt;{product.name}&lt;/h3&gt;<br>                      &lt;p&gt;{product.description}&lt;/p&gt;<br>                      &lt;p&gt;{product.price}&lt;/p&gt;<br>                      &lt;p className=&quot;quantity&quot;&gt;<br>                      &lt;button onClick={() =&gt; addToCart(product.id)} className=&quot;cart-btn&quot;&gt;<br>                      Add To Cart<br>                      &lt;/button&gt;                   <br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;crimson&quot;, product.id)} <br>                        className=&quot;select-color crimson&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;green&quot;, product.id)} <br>                        className=&quot;select-color green&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;violet&quot;, product.id)} <br>                        className=&quot;select-color violet&quot;&gt;+&lt;/span&gt;<br>                      &lt;span <br>                        onClick={() =&gt; handleColor(&quot;black&quot;, product.id)} <br>                        className=&quot;select-color black&quot;&gt;+&lt;/span&gt;<br>                      &lt;/p&gt;<br>                    &lt;/div&gt;<br>                ))<br>            }<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default DeriveState;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*uoTy6bEZK9yT5hWfuuNaJQ.png" /><figcaption>The UI of Derive state component</figcaption></figure><p>Now we can see the selected color on the page. We also removed the copy selected product and just stored the id of it.</p><p><strong>Thank you for reading this far. I hope now you understood the common mistakes React developer makes when comes to using the useState hook. And you are ready to avoid these mistakes in your next project.</strong></p><h4>If you want more such content then do follow me on <a href="https://rajeshi.medium.com/">Medium </a>and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h4><p>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></p><h4>More content at <a href="https://plainenglish.io/">PlainEnglish.io</a>.</h4><p>Sign up for our <a href="http://newsletter.plainenglish.io/"><strong>free weekly newsletter</strong></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><strong>Twitter</strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong>, and</strong> <a href="https://discord.gg/GtDtUAvyhW"><strong>Discord</strong></a><strong>.</strong></p><h4>Interested in scaling your software startup? Check out <a href="https://circuit.ooo/?utm=publication-post-cta">Circuit</a>.</h4><p>We offer free expert advice and bespoke solutions to help you build awareness and adoption for your tech product or service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde757ca52f5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-usestate-hook-mistakes-you-must-avoid-fde757ca52f5">React useState hook Mistakes You Must Avoid!</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[What is useRef hook & forwardRef in React? A Complete Explanation]]></title>
            <link>https://javascript.plainenglish.io/what-is-useref-hook-forwardref-in-react-a-complete-explanation-8f55496875ca?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f55496875ca</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[forwardref]]></category>
            <category><![CDATA[useref]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 09:59:22 GMT</pubDate>
            <atom:updated>2022-12-15T03:10:18.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lv9RxaGChfDUs-Jp2WY-eA.png" /></figure><p>In this blog, we will go through a complete discussion of the useRef hook and forwardRef in react. We will understand the use cases of the useRef hook with some examples and see the importance of forwardRef. At the end of the blog, you will have a complete understanding of useRef hook and forwardRef in React.</p><h3>What is the useRef hook in React?</h3><p>The useRef is a React hook that allows you to directly create a reference to the DOM element and returns a ref object with a single current property initially set to the initial value you provided.</p><pre>import { useRef } from &#39;react&#39;;<br>const ref = useRef(initialValue)</pre><h4>Let us simplify the definition by the following points</h4><ol><li><strong>Access DOM element: </strong>useRef hook allows you to access an element in the DOM. we can add a ref attribute to an element to access it directly.</li></ol><p><strong>Access DOM element usging useRef hook</strong></p><pre>import { useRef } from &#39;react&#39;;<br><br>const Blog = () =&gt; {<br>    const inputElement = useRef();<br>  <br>    const handleClick = () =&gt; {<br>      console.log(&quot;inputElement: &quot;, inputElement);<br>      console.log(&quot;current: &quot;, inputElement.current);<br>    };<br>  <br>    return (<br>      &lt;div className=&quot;main-component&quot;&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>            &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>            &lt;input <br>             type=&quot;text&quot; <br>             className=&quot;input-field&quot; <br>             placeholder=&quot;Enter your email&quot; <br>             id=&quot;email&quot; <br>             ref={inputElement}<br>            /&gt;<br>        &lt;/div&gt;<br>        &lt;button className=&quot;submit&quot; onClick={handleClick}&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>};<br><br>export default Blog;</pre><p><strong>The Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzSRD8JyI0hkWWeB0oG4nw.png" /><figcaption>Accessing input element using useRef hook</figcaption></figure><p>As you can see useRef returns a ref object (inputElement in our example) with a single current property which is actually having the dom element.</p><p><strong>2. Does Not Cause Re-renders: </strong>When we update the data of the useState hook it re-renders the component in order to reflect new changes on the web page. But in the case of the useRef hook, it does not cause re-rendering when updating the value.</p><p>Let us look at an example below. Firstly we will see the implementation using useState hook and later improve it using the useRef hook.</p><blockquote>Implementing login form using useState hook</blockquote><pre>import { useEffect, useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const [formData, setFormData] = useState({email: &quot;&quot;, password: &quot;&quot;});<br><br>  const handleChange = name =&gt; event =&gt; {<br>    setFormData({...formData, [name]: event.target.value})<br>  }<br><br>  const handleSubmit = () =&gt; {<br>    console.log(&quot;RESULT: &quot;, formData);<br>  }<br>  <br>  useEffect(()=&gt; {<br>    console.log(&quot;APP COMPONENT RENDERED&quot;);<br>  })<br>  return (<br>    &lt;div className=&quot;parent-component&quot;&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>        &lt;input <br>         type=&quot;email&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your email&quot; <br>         id=&quot;email&quot; <br>         onChange={handleChange(&quot;email&quot;)}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Enter your Password&lt;/label&gt;<br>        &lt;input <br>         type=&quot;password&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your password&quot; <br>         id=&quot;password&quot; <br>         onChange={handleChange(&quot;password&quot;)}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>The output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*3ey5ZQGc_0lC89zsvbuqhQ.png" /><figcaption>Component re-renders due to state update</figcaption></figure><p>In the above example, you can see as well fill the form each character input causes the state to update, and hence component keeps on getting re-render.</p><p>We can avoid the continuous re-rendering of the component using the useRef hook. Let us see the same implementation using the useRef hook.</p><blockquote>Implementing login form using useRef hook</blockquote><pre>import { useEffect, useRef } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const emailField = useRef(&quot;&quot;);<br>  const passwordField = useRef(&quot;&quot;);<br><br>  const handleSubmit = () =&gt; {<br>    if(emailField.current.value === &quot;&quot;) {<br>      emailField.current.focus();<br>      return;<br>    }<br>    console.log(&quot;Email: &quot;, emailField.current.value);<br>    console.log(&quot;Password: &quot;, passwordField.current.value);<br>  }<br>  <br>  useEffect(()=&gt; {<br>    console.log(&quot;APP COMPONENT RENDERED&quot;);<br>  })<br>  return (<br>    &lt;div className=&quot;parent-component&quot;&gt;<br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>        &lt;input <br>         type=&quot;email&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your email&quot; <br>         id=&quot;email&quot; <br>         ref={emailField}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;input-control&quot;&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Enter your Password&lt;/label&gt;<br>        &lt;input <br>         type=&quot;password&quot; <br>         className=&quot;input-field&quot; <br>         placeholder=&quot;Enter your password&quot; <br>         id=&quot;password&quot; <br>         ref={passwordField}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>The output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*s1_0c0B8X4YdLzN_A45Lgw.png" /><figcaption>Avoiding re-rendering using useRef hook</figcaption></figure><p>We can see that there is no re-rendering using the useRef hook.</p><h3>Introduction to forwardRef</h3><p>Considering the above login form example now I want to create a separate custom input component in order to make our code more modular and reusable.</p><p>Let us quickly look at this implementation and see the result.</p><p><strong>ForwardApp component</strong></p><pre>import { useEffect, useRef } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>import CustomInput from &quot;./CustomInput&quot;;<br><br>function ForwardApp() {<br>  const emailField = useRef(&quot;&quot;);<br>  const passwordField = useRef(&quot;&quot;);<br><br>  const handleSubmit = () =&gt; {<br>    if(emailField.current.value === &quot;&quot;) {<br>      emailField.current.focus();<br>      return;<br>    }<br>    console.log(&quot;Email: &quot;, emailField.current.value);<br>    console.log(&quot;Password: &quot;, passwordField.current.value);<br>  }<br>  <br>  useEffect(()=&gt; {<br>    console.log(&quot;APP COMPONENT RENDERED&quot;);<br>  })<br>  return (<br>    &lt;div className=&quot;parent-component&quot;&gt;<br>      &lt;CustomInput<br>        type=&quot;email&quot; <br>        className=&quot;input-field&quot; <br>        placeholder=&quot;Enter your email&quot; <br>        id=&quot;email&quot;  <br>        ref={emailField}<br>      /&gt;<br>      &lt;CustomInput<br>        type=&quot;password&quot; <br>        className=&quot;input-field&quot; <br>        placeholder=&quot;Enter your password&quot; <br>        id=&quot;password&quot; <br>        ref={passwordField} <br>       /&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ForwardApp;</pre><p><strong>CustomInput component</strong></p><pre>const CustomInput = (props, ref) =&gt; {<br>    return (<br>        &lt;div className=&quot;input-control&quot;&gt;<br>            &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>            &lt;input {...props} /&gt;<br>        &lt;/div&gt;<br>    )};<br><br>export default CustomInput;</pre><p><strong>The output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgdLxsFoXst69-KAFtp2zA.png" /><figcaption>Error while passing ref to child component</figcaption></figure><p>The reason behind the error is that we cannot pass the ref from the parent component to the child component directly as a prop. So we got an error that is saying us to use forwardRef and please ignore the warnings of dev tools. Let us discuss what is forwardRef in detail.</p><h3>What is forwardRef in React?</h3><p>In React forwardRef is a method that allows parent components to pass down ref to their children. The forwardRef gives reference to a DOM element created by its parent component to the child component. This then allows the child to read and modify that element anywhere it is being used.</p><p>Let us fix the error we got using forwardRef.</p><p><strong>ForwardApp component</strong></p><pre>import { useEffect, useRef } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>import CustomInput from &quot;./CustomInput&quot;;<br><br>function ForwardApp() {<br>  const emailField = useRef(&quot;&quot;);<br>  const passwordField = useRef(&quot;&quot;);<br><br>  const handleSubmit = () =&gt; {<br>    if(emailField.current.value === &quot;&quot;) {<br>      emailField.current.focus();<br>      return;<br>    }<br>    console.log(&quot;Email: &quot;, emailField.current.value);<br>    console.log(&quot;Password: &quot;, passwordField.current.value);<br>  }<br>  <br>  useEffect(()=&gt; {<br>    console.log(&quot;APP COMPONENT RENDERED&quot;);<br>  })<br>  return (<br>    &lt;div className=&quot;parent-component&quot;&gt;<br>      &lt;CustomInput<br>        type=&quot;email&quot; <br>        className=&quot;input-field&quot; <br>        placeholder=&quot;Enter your email&quot; <br>        id=&quot;email&quot;  <br>        ref={emailField}<br>      /&gt;<br>      &lt;CustomInput<br>        type=&quot;password&quot; <br>        className=&quot;input-field&quot; <br>        placeholder=&quot;Enter your password&quot; <br>        id=&quot;password&quot; <br>        ref={passwordField} <br>       /&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleSubmit} className=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/div&gt;<br><br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ForwardApp;</pre><p><strong>CustomInput component</strong></p><pre>import { forwardRef } from &quot;react&quot;;<br><br>const CustomInput = forwardRef((props, ref) =&gt; {<br>    return (<br>        &lt;div className=&quot;input-control&quot;&gt;<br>            &lt;label htmlFor=&quot;email&quot;&gt;Enter your Email&lt;/label&gt;<br>            &lt;input {...props} ref={ref}/&gt;<br>        &lt;/div&gt;<br>    )}<br>);<br><br>export default CustomInput;</pre><p><strong>The output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*RIpnIfu_g2YJSCczBeK4uw.png" /><figcaption>used forwardRef to fix the error</figcaption></figure><p>Now that we understood the useRef hook and forwardRef in React. Let us quickly summarize them below.</p><h4>useRef hook summary:</h4><ol><li>It can be used to access a DOM element directly.</li><li>It can be used to store a value that does not cause a re-render when updated.</li></ol><h4><strong>forwardRef summary:</strong></h4><p>The forwardRef allows you to pass the reference of a DOM element from the parent component to the child component.</p><p><strong>Thank you for reading this far. I hope now you understood the useRef hook and forwardRef in react.</strong></p><h3>If you want more such content then do follow me on Medium and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><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>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f55496875ca" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-is-useref-hook-forwardref-in-react-a-complete-explanation-8f55496875ca">What is useRef hook &amp; forwardRef in React? A Complete Explanation</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[Learn useReducer() Hook and Manage Complex States]]></title>
            <link>https://javascript.plainenglish.io/learn-usereducer-hook-and-manage-complex-states-a-complete-guide-2f91c789abb8?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f91c789abb8</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usereducer]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 15:43:38 GMT</pubDate>
            <atom:updated>2022-11-29T01:16:02.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>A complete guide on useReducer() hook and managing complex states.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apKUrFNK07hb5oYKI6Lc8A.png" /></figure><p>In this blog, we will go through a complete discussion of the useReducer() hook in react. We will understand the need for it, when to use it, and how to use it.</p><h3>State management in react component</h3><p>There are two hooks to manage the state in react component and these are:</p><ol><li>useState and</li><li>useReducer</li></ol><h3>useState hook and its problem</h3><p>If we talk about handling state in the react functional component then immediately useState() hook comes to our mind. We store the data using the useState() hook, wait for some action to trigger, and based on the action the data of state gets updated and it triggers the rendering of a component through which the new changes get reflected on the web page. That’s how the useState() hook works.</p><p>useState() hook allows you to store a single unit of data whether it may be a boolean, string, array, or object. The real challenges appear when you need to store multiple units of data in one single component which means creating multiple useState() hooks. And all these multiple useState() hooks are going to make your code less readable, and less manageable which in turn is going to impact the code quality.</p><h3>Centralizing component data with useReducer() hook</h3><p>As discussed above, having multiple useState in a single component is going to impact the code quality. So what if we centralize all the component data in one single place and manipulate from there?</p><p>Sounds cool right?</p><p>By now you might have guessed, Yes useReducer() hook is all about centralizing all the component data in one single place and managing it from there. It is similar to Redux but is quite easy to implement, unlike Redux.</p><pre>const INIT_STATE = {<br>    todo: [{id: 1, title: &#39;Go to gym&#39;}]<br>}<br>function todoReducer(state, action) {}<br>const [state, dispatch] = useReducer(todoReducer, INIT_STATE);</pre><p>The useReducer() hook takes two arguments:</p><ol><li><strong>Initial state:</strong> The initial state (INIT_STATE) is the state of the component that is initialized with some value.</li><li><strong>Reducer function:</strong> The reducer is a pure function that accepts two parameters: the current state and an action object. Depending on the action object, the reducer function must update the state in an immutable manner, and return the new state.</li></ol><pre>function todoReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;ADD_TODO&#39;:<br>      return {...state, todo: action.payload};<br>    default:<br>      return {...state};<br>  }<br>}</pre><p>The useReducer() hook then returns an array of two items: the current state and the dispatch function.</p><p><strong>Dispatch function:</strong> The dispatch() function is used whenever you want to update the state just like calling the setState(). You simply call the dispatch() function and pass the appropriate action object.</p><pre>dispatch({<br>   type: &#39;ADD_TODO&#39;, <br>   payload: [...state.todo, {id: 123, title: &#39;Learn React hooks&#39;}]<br>});</pre><h3>The working process of useReducer() hook</h3><p>Based on certain events or actions done the component calls the dispatch function which sends the action object to the Reducer function. The reducer function then based on the action type returns a new state which gets reflected on the web page.</p><p>Look at the mini project below that implements the useReducer() hook. The project is a small social media type project that lets you post random things.</p><blockquote><strong>App.js</strong></blockquote><pre>import &#39;./App.css&#39;;<br>import BetterMicroBlog from &#39;./BetterMicroBlog&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;parent-component&quot;&gt;<br>    &lt;BetterMicroBlog /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><blockquote><strong>BetterMicroBlog.js</strong></blockquote><pre>import { useReducer, useRef } from &quot;react&quot;;<br>import &quot;./MicroBlog.css&quot;;<br><br>const BetterMicroBlog = () =&gt; {<br><br>    const postInput = useRef();<br><br>    const INIT_STATE = {<br>        data: [{id: Date.now(), content: &quot;React is awesome 🔥&quot;}],<br>        emptyMsg: false<br>    }<br><br>    function blogReducer(state, action) {<br>        switch(action.type) {<br>            case &quot;ADD_POST&quot;:<br>                return {...state, data: action.payload, emptyMsg: false};<br>            case &quot;DELETE_POST&quot;:<br>                return {...state, data: action.payload, emptyMsg: false};<br>            case &quot;EMPTY_MSG&quot;:<br>                return {...state, emptyMsg: action.payload}<br>            default:<br>                return {...state};<br>        }<br>    }<br><br>    const [state, dispatch] = useReducer(blogReducer, INIT_STATE);<br>    <br>    function addPost() {<br>        const inputValue = postInput.current.value;<br>        if (inputValue !== &quot;&quot;) {<br>            dispatch({<br>                type: &quot;ADD_POST&quot;, <br>                payload: [...state.data, {id: Date.now(), content: inputValue}]<br>            });<br>            postInput.current.value = &quot;&quot;;<br>            return;<br>        }<br>        dispatch({<br>            type: &quot;EMPTY_MSG&quot;,<br>            payload: true<br>        })<br>    }<br><br>    function deletePost(postId) {<br>        dispatch({<br>            type: &quot;DELETE_POST&quot;, <br>            payload: [...state.data.filter(post =&gt; post.id !== postId)]<br>        });<br>    }<br><br>    return (<br>    &lt;div className=&quot;micro-blog&quot;&gt;<br>    {<br>        state.emptyMsg ? <br>        &lt;div className=&quot;empty-msg&quot;&gt;Please write something!&lt;/div&gt;<br>        : null<br>    }<br>        &lt;div className=&quot;micro-blog-head&quot;&gt;<br>            &lt;h2&gt;What&#39;s happening?&lt;/h2&gt;<br>            &lt;input<br>             type=&quot;text&quot; <br>             className=&quot;blog-input&quot;<br>             placeholder=&quot;Say Something!&quot; <br>             ref={postInput}<br>            /&gt;<br>            &lt;button onClick={addPost} className=&quot;post-btn&quot;&gt;<br>            Add Post<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>        {<br>            state.data.map(post =&gt; (<br>                &lt;div key={post.id} className=&quot;post-content&quot;&gt;<br>                    &lt;p&gt;{post.content}&lt;/p&gt;<br>                    &lt;div&gt;<br>                    &lt;button<br>                     onClick={() =&gt; deletePost(post.id)} <br>                     className=&quot;delete-btn&quot;&gt;<br>                     Delete<br>                     &lt;/button&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            ))<br>        }<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default BetterMicroBlog;</pre><blockquote><strong>The Output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*3Fod56OxxC3-uO2vZDFKkQ.png" /><figcaption>Output</figcaption></figure><p><strong>Thank you for reading this far. I hope now you understood the useReducer() hook in react and its importance.</strong></p><h3>If you want more such content then do follow me on Medium and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a>.</h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a>.</h3><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>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f91c789abb8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/learn-usereducer-hook-and-manage-complex-states-a-complete-guide-2f91c789abb8">Learn useReducer() Hook and Manage Complex States</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[useCallback() hook to improve React component performance: A complete guide]]></title>
            <link>https://blog.devgenius.io/usecallback-hook-to-improve-react-component-performance-a-complete-guide-89bd4997574c?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bd4997574c</guid>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[memo]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 16:16:33 GMT</pubDate>
            <atom:updated>2022-11-14T08:59:43.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8TByBnpic9g8zBy1XpLiQ.png" /></figure><p>In this blog, we are going to understand the <strong>useCallback()</strong> hook in <strong>React</strong>. We will start with an introduction and see the code implementation of it. We will also discuss how and when to use the useCallback() hook.</p><p>Before we move further with the useCallback() hook you need to understand <a href="https://blog.devgenius.io/react-memo-and-usememo-explained-in-the-right-way-you-should-know-this-af10a805e620"><strong>memoization in React</strong></a> using the useMemo() hook and react memo(). Here, I am going to explain the react memo in brief, If you need a detailed explanation then please click <a href="https://blog.devgenius.io/react-memo-and-usememo-explained-in-the-right-way-you-should-know-this-af10a805e620"><strong>here</strong></a></p><h3>React re-rendering and performance pitfall</h3><p>We all know that a react component renders when its state or props changes and all the child components render as well. And In some cases, we might have a situation where the parent component renders but there is no rendering required in the child component because both the state and props of the child component haven’t changed but the child component still renders because of the fact that parent component is re-rendering which is going to be a performance pitfall due to unnecessary rendering.</p><blockquote>Let us see an example of unnecessary re-rendering</blockquote><blockquote><strong>App.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca49c3e90f21b72116b7feeb702c71e1/href">https://medium.com/media/ca49c3e90f21b72116b7feeb702c71e1/href</a></iframe><blockquote><strong>Child.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826098dcc95003b057e00c1166f5c29e/href">https://medium.com/media/826098dcc95003b057e00c1166f5c29e/href</a></iframe><blockquote><strong>The output </strong>(Intitial rendering when page loads)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*l0BMFBDP1pRag8JcZOGd7A.png" /><figcaption>Output when the page is loading</figcaption></figure><blockquote><strong>The output</strong> (when the parent component re-renders)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*3B-YmMnHqsJrbF3LTzYP_g.png" /><figcaption>Output when the parent component re-renders</figcaption></figure><p>In the above code snippets and their output, we can see that when the parent component re-renders, the props or state of the child component does not change but it still re-renders and produce the same output due to the parent component re-rendering and we all know that unnecessary re-rendering of any component is a performance pitfall. And in order to avoid such unnecessary re-rendering we use react memo.</p><h3>React memo and its importance</h3><p>React memo memoizes the react component and allows it to re-render only when its props or state changes. Thus, improving the performance of react component.</p><blockquote>Let us use react memo and avoid unnecessary re-rendering</blockquote><blockquote><strong>App.js component is going to be same as the above.</strong></blockquote><blockquote><strong>Child.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca020058173bd372adde145f3b2c36d2/href">https://medium.com/media/ca020058173bd372adde145f3b2c36d2/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*8fg6_R1ZBK-2i_1ipvSI7A.png" /><figcaption>The output of memoized child component with no unnecessary re-rendering</figcaption></figure><p>In the above example, we use memo() to memoize our child component and avoided unnecessary re-rendering.</p><blockquote>Let us add a functionality to add data in the child component just like the parent component (App.js)</blockquote><blockquote><strong>App.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf78623071c0535443c345b7c4c78a3/href">https://medium.com/media/dcf78623071c0535443c345b7c4c78a3/href</a></iframe><blockquote><strong>child.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32fbecfa0b907db31dae8ee63ecc0035/href">https://medium.com/media/32fbecfa0b907db31dae8ee63ecc0035/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*2ltKJcjFbCPrQPQvBUE2FQ.png" /></figure><p>Now when we added functionality to add data in the child component somehow our memoize child component is not working. When the parent component re-renders the child component re-renders too. This is because we are passing a function (addChildData) to the child component which is declared in the parent component.</p><p>Whenever the parent component re-renders, the function (addChildData) gets recreated and stored in a new memory location with a new memory reference, and hence the memoize child component re-renders because the reference of addChildData prop was changed. And this change in reference to the same function causes re-rendering which can be solved using the useCallback() hook.</p><h3>Introduction to useCallback() hook</h3><p>useCallback() is a hook that helps us to improve the react component performance by memoizing or caching a function between re-renders.</p><p>When a component re-renders, every function inside the component is recreated, and therefore the memory location where these functions are stored gets changed as well. It also means the address or the reference of these functions changes.</p><p>The useCallback() hook returns a memoized callback function which is passed as a prop to the child component. This means that instead of recreating the function on every re-render, we can use the same function between renders, and by doing so we can prevent unnecessary renders.</p><p>The useCallback hook only runs when one of its dependencies changes.</p><h4>You need to pass two things to useCallback:</h4><ol><li>A function definition that you want to cache between re-renders.</li><li>A list of dependencies including every value within your component that’s used inside your function.</li></ol><pre>const cachedFn = useCallback(function, dependencies)</pre><blockquote>Let us implement useCallback() hook to memoize or cache the function and avoid unnecessary re-rendering</blockquote><blockquote><strong>App.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37ea2e2cdbe41faff17a0482fdffad7/href">https://medium.com/media/a37ea2e2cdbe41faff17a0482fdffad7/href</a></iframe><blockquote><strong>Child.js</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06369e5d6797c0b468b85fbc7c7d93b4/href">https://medium.com/media/06369e5d6797c0b468b85fbc7c7d93b4/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*FfOZRtXm-V1KL48nq-GzCA.png" /><figcaption>The output after implementing the useCallback() hook</figcaption></figure><p>With the implementation of the useCallback hook, we successfully avoided unnecessary re-rendering and thus improve the performance of react component.</p><h3>When not to use the useCallback() hook?</h3><p>The useCallback() hook is mainly used to optmize performance by memoizing the expensive function. And it is done by adding a list of dependencies but if you fill your entire component with unnecessary useCallback() the performance will go downwards.</p><p><strong>Thank you for reading this far. I hope now you understood the useCallback() hook in react and its importance.</strong></p><h3>If you want more such content then do follow me on Medium and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a></h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bd4997574c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/usecallback-hook-to-improve-react-component-performance-a-complete-guide-89bd4997574c">useCallback() hook to improve React component performance: A complete guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React.memo and useMemo explained in the right way: You should know this]]></title>
            <link>https://blog.devgenius.io/react-memo-and-usememo-explained-in-the-right-way-you-should-know-this-af10a805e620?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/af10a805e620</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 08:59:59 GMT</pubDate>
            <atom:updated>2022-11-06T16:15:12.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNaW1CID8rDNX-bdrjdeTw.png" /></figure><p>In this blog, we are going to understand <strong>React.memo</strong> and <strong>useMemo </strong>hook. We will start with an introduction and move forward with some examples and see which one to use when.</p><p>Before we start with <strong>React.memo</strong> and <strong>useMemo</strong>, Firstly we need to understand <a href="https://rajeshi.medium.com/learn-memoization-in-javascript-to-optimize-your-code-653dc5cb36cc"><strong>What is memoization?</strong></a><strong> </strong>and then we will move forward with the React concepts of memoization.</p><h3>Introduction to memoization</h3><p>Memoization is an optimization technique where the results or output of an expensive function call are cached such that the result can be immediately returned the next time the function is called with the same input.</p><p>In simple terms, We run a function once with the input given and cache/store its result somewhere. So that the next time the function is called with the same input we simply returned the stored value instead of running the whole function again.</p><p>By not running the whole function again we save some of our computation time and hence we end up making our code faster. You can read more about memoization by clicking <a href="https://rajeshi.medium.com/learn-memoization-in-javascript-to-optimize-your-code-653dc5cb36cc"><strong>here</strong></a></p><h3>Introduction to re-rendering and memoization in React?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vrwOjcZCNJL2yb7m" /><figcaption>Photo by <a href="https://unsplash.com/@chatelp?utm_source=medium&amp;utm_medium=referral">Pierre Châtel-Innocenti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To better understand memoization in React you need to know when React re-renders components.</p><p>React re-renders components when the props or state is changed. And when a component is re-rendering, all the children components will also re-render.</p><h3>The problem with re-rendering the component</h3><p>Re-rendering the component means re-rendering all the child components as well, although the props and state of the child component may not be changed and it will return the same output as before. Component re-rendering goes through a complex computational process.</p><p>The re-rendering of child components without changing any of its prop or states is a performance pitfall. It is going to make our code less performant. And to handle this issue React introduced the higher-order component called React.memo</p><h3>Introduction to React.memo</h3><p>React components are just JavaScript functions that return JSX based on some computation. So react offers us React.memo to memoize the components. This prevents the re-rendering of the components and allows only when dependencies like props have changed.</p><h3>When to memoize react component?</h3><p>It is best to memoize only when the component is heavy and has some complex computations to perform. You should not use memoization in every component because memoization uses memory and can be less performant in certain cases.</p><h3>When not to memoize react component?</h3><p>You should avoid using React.memo when the component computation is not complex enough and props keep on changing where the component won’t be receiving the same props.</p><h3>How to implement memoization in react component?</h3><blockquote>First, let us see an example without implementing memoization.</blockquote><blockquote><strong>App.js component (Parent)</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bba204fdeeb02c4b1c0d51eb1e8a5a3/href">https://medium.com/media/2bba204fdeeb02c4b1c0d51eb1e8a5a3/href</a></iframe><blockquote><strong>Child.js component (Children)</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6525c3cdb8f0e90e9807dabebce7f7d/href">https://medium.com/media/c6525c3cdb8f0e90e9807dabebce7f7d/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*TB_smlwt5-RV_QWeKUPMdw.png" /></figure><p>As you can see, when we click the “Add parent data” button it also renders the child component as well. But the prop of the child component is the same as earlier. So the child component should not re-render again.</p><blockquote>Implementing memoization to the child component</blockquote><blockquote>The App.js component is going to be completely the same. We just need to memoize the child component.</blockquote><blockquote><strong>Child.js component</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca044c5a07b582d99615833cee14c82/href">https://medium.com/media/1ca044c5a07b582d99615833cee14c82/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*jL1oDNeWN_HHk5_vFvPbnQ.png" /></figure><p>Now you can see, when we click multiple times on the “Add parent data” button only the parent component gets re-render and not the child component. The child component is rendered only when the page is loaded and if the props or state of the child component gets changed</p><h4>The drawback of React.memo</h4><p>By default React.memo does a shallow comparison of props. It means it checks only whether the top level prop is changed or not. You can add a second argument to customize the props comparison.</p><pre>React.memo(Component, [areEqual(prevProps, nextProps)]);</pre><blockquote>With React.memo being sorted, now let us move towards useMemo and see what it is</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mMlVd_B3QRkz-ih5" /><figcaption>Photo by <a href="https://unsplash.com/@terra_gallery?utm_source=medium&amp;utm_medium=referral">TERRA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When a component goes through re-rendering every function declared inside the component gets executed again. And there might be a function that is computation heavy but often gets the same input and hence returns the same output.</p><p>In this case, instead of executing the function at every component re-render we can memoize the function inside the component itself and improve the performance of our application. And this can be achieved using the useMemo() hook.</p><h3>What is the useMemo hook?</h3><p>The useMemo hook can be used to prevent expensive, resource intensive functions from needlessly running inside the component which results in the same output.</p><h4><strong>You need to pass two things to useMemo:</strong></h4><ol><li>An expensive function that needs to be memoized.</li><li>A dependency array that includes every value within your component that’s used inside your expensive function.</li></ol><pre>import { useMemo } from &#39;react&#39;;<br>const value = useMemo(() =&gt; expensiveFunction(param), [param]);</pre><h3>How to implement useMemo in a function?</h3><blockquote>First, let us see an example without implementing useMemo.</blockquote><blockquote><strong>App.js component</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e16b7e1f2cf52b2468dda85ec31618a/href">https://medium.com/media/2e16b7e1f2cf52b2468dda85ec31618a/href</a></iframe><blockquote>HookComponent.js</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b91ff3fec08d02fb0c3cb634848b0f0/href">https://medium.com/media/3b91ff3fec08d02fb0c3cb634848b0f0/href</a></iframe><blockquote><strong>The output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*gfm-WTivRirXYQ5NMA_sbA.png" /></figure><p>As you can see, when we click the “Load more Shoes” button the totalTshirts function gets executed because the component gets re-render. Here, we clearly know that the totalTshirts function is going to give us the same output as previously when clicking on the “Load more Shoes” button. So we can memoize this totalTshirts function and can optimize our code.</p><blockquote>Implementing useMemo to the HookComponent</blockquote><blockquote>The App.js component is going to be completely the same. We just need to memoize the HookComponent.js.</blockquote><blockquote><strong>HookComponent.js component</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2035a03397c13336696ce1efcc538c/href">https://medium.com/media/5c2035a03397c13336696ce1efcc538c/href</a></iframe><blockquote><strong>The Output</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*kbDOVJWkIWmMDkNEOw6NZA.png" /></figure><p>Wooh now when we click the “Load more shoes” button multiple times the memoizedTotalTshirts function did not get executed and it ran only once when the page was loading.</p><h3>The major difference between React.memo and useMemo hook</h3><ol><li>React.memo is a higher-order component to memoize an entire functional component.</li><li>useMemo is a react hook to memoize a function within a functional component.</li></ol><p><strong>Thank you for reading this far. I hope now you understood memoization in react and its importance.</strong></p><h3>If you want more such content then do follow me on Medium and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a>.</h3><h3>Any doubt? reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af10a805e620" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-memo-and-usememo-explained-in-the-right-way-you-should-know-this-af10a805e620">React.memo and useMemo explained in the right way: You should know this</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Memoization in JavaScript to optimize your code.]]></title>
            <link>https://medium.com/swlh/learn-memoization-in-javascript-to-optimize-your-code-653dc5cb36cc?source=rss-df6dad62b19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/653dc5cb36cc</guid>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajesh Bhattarai]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 15:06:52 GMT</pubDate>
            <atom:updated>2022-10-22T15:06:52.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Memoization in JavaScript.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6ENOQx3gM4IInHJ" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog, we are going to start with the introduction of memoization in JavaScript and then move forward to see How and When to use it?</p><p>Firstly, I am going to show you an easy and simple example so that you get comfortable with the concepts, and then we will see how we actually use memoization using core JavaScript concepts like closures, higher order functions, etc.</p><h3>What is Memoization?</h3><p>Memoization is an optimization technique where the results or output of an expensive function call are cached such that the result can be immediately returned the next time the function is called with the same input.</p><p><strong>oh boy,</strong> let us make this definition a bit simpler now. In simple terms, we have a function that consists of many lines of code and it takes a long time to execute it and give us the result. Also, we need to execute this function multiple times. We already know running this function just once takes a long time to give us the result. Now we need to run it multiple times which means we are making our code slow.</p><p>So, <strong>Is there a way where we can run our expensive function multiple times without making our code slow?</strong></p><p>We will run this expensive function once for a particular input and then cache (store) the result of it. So that next time if the function is called with the same input then instead of running the expensive time consuming function we will simply take the result from the cache. And that’s how we prevent our code from being slow. <strong>This process is called memoization.</strong></p><h3>How to use memoization in JavaScript?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sbiwsLpinELH7M7y" /><figcaption>Photo by <a href="https://unsplash.com/@mattwridley?utm_source=medium&amp;utm_medium=referral">Matt Ridley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let us consider an example and see how we use memoization in JavaScript.</p><p>I want to write a function that is going to check whether a given input is a palindrome or not.</p><h3>Implementation of memoization in JavaScript</h3><pre>const cachePalinChecker = {};<br>function palindromeChecker(string) {<br>  <strong><em>// Checking in cache</em></strong><em><br>  </em>if(cachePalinChecker[string] != null) {<br>      console.log(&quot;Value getting from cache&quot;);<br>      console.log(string + &quot; is &quot; + cachePalinChecker[string]);<br>      return;<br>   }<br>const arrayValues = string.split(&#39;&#39;);<br>const reverseArrayValues = arrayValues.reverse();<br>const reverseString = reverseArrayValues.join(&#39;&#39;);<br>if(string == reverseString) {<br>   <strong><em>// Storing in the cache for the first time</em></strong><em><br>   </em>cachePalinChecker[string] = &quot;palindrome&quot;;<br>   console.log(&quot;Regular Calculation&quot;);<br>   console.log(string + &quot; is &quot; + cachePalinChecker[string]);<br>   return;<br>}<br><strong><em>// Storing in the cache for the first time</em></strong><em><br></em>cachePalinChecker[string] = &quot;not palindrome&quot;;<br>console.log(&quot;Regular Calculation&quot;);<br>console.log(string + &quot; is &quot; + cachePalinChecker[string]);<br>return;<br>}<br>palindromeChecker(&quot;madam&quot;);<br>palindromeChecker(&quot;racecar&quot;);<br>palindromeChecker(&quot;racecar&quot;);<br>palindromeChecker(&quot;madam&quot;);<br>palindromeChecker(&quot;john&quot;);<br>palindromeChecker(&quot;john&quot;);</pre><h4>The output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*xGe11CxxEE78sY4aLEkXJw.png" /><figcaption>output</figcaption></figure><p>As you can see in the above example, we cache or store the output of the <strong>palindromeChecker()</strong> function in an object (<strong>cachePalinChecker</strong>) when it is running with a unique input for the first time. But as soon as we run the function next time with the same input, it first checks in the cache and then returns the result from it without having to perform all the operations again.</p><p>So that was the simple implementation of memoization in JavaScript. Now, let us see another example where we use core JavaScript concepts like closures, higher order functions to implement memoization.</p><h3>Implementation of memoization using core JavaScript concepts</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa42f9ec6fbe48fa995fa62f53af4859/href">https://medium.com/media/fa42f9ec6fbe48fa995fa62f53af4859/href</a></iframe><h4>The output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*8bJ2TQ8QzFLDluOCRVPvqQ.png" /><figcaption>output</figcaption></figure><p>In the above example, we used core JavaScript concepts to implement memoization. As you can see, we have a <strong>square()</strong> function that gives the square of a number. And we cached the result every time the function is called with a unique input. And if the input is similar then instead of executing the whole function again, we just returned the result from the cache.</p><p><strong>Thank you for reading this far. I hope now you understood memoization and it’s importance.</strong></p><h3>If you want more such content then do follow me on Medium and subscribe to my <a href="https://www.youtube.com/channel/UCgfW-cxlW7NlpbOscKJYkfA">YouTube channel</a>.</h3><h3>You can also reach me on <a href="https://twitter.com/izrajesh">Twitter</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653dc5cb36cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/learn-memoization-in-javascript-to-optimize-your-code-653dc5cb36cc">Learn Memoization in JavaScript to optimize your code.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>