<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Kunal Nalawade - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Kunal Nalawade - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:48 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/KunalN25/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Website from Scratch – Start to Finish Walkthrough ]]>
                </title>
                <description>
                    <![CDATA[ Hi, fellow developers! Building a website can feel overwhelming at first – especially when you're staring at a blank HTML file, wondering how it ever turns into a real website on the internet. If you're new to web development, you've probably asked y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-website-from-scratch-start-to-finish-walkthrough/</link>
                <guid isPermaLink="false">680fd51ef631538076304a73</guid>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 28 Apr 2025 19:21:02 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745260046049/62b5c730-dc06-49de-8bdd-2cd44facb9e9.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi, fellow developers!</p>
<p>Building a website can feel overwhelming at first – especially when you're staring at a blank HTML file, wondering how it ever turns into a real website on the internet. If you're new to web development, you've probably asked yourself: <em>"Where do I even start?"</em></p>
<p>Well, this tutorial is here to guide you through that journey. We'll build a simple website from scratch and walk through every step — all the way to deploying it on the internet.</p>
<p>Let’s dive in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-starting-with-the-website-idea">Starting with the Website Idea</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-the-project">How to Set Up the Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-the-website">How to build the website</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-the-code">How to test the code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-push-your-code-to-version-control">How to Push your code to Version Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deployment-and-hosting">Deployment and Hosting</a></p>
</li>
</ol>
<h2 id="heading-starting-with-the-website-idea">Starting with the Website Idea</h2>
<p>We are going to a build a simple weather app that shows you today’s weather in your city. It will have the following features:</p>
<ul>
<li><p>Search by city name: User enters city name and fetches weather information</p>
</li>
<li><p>Display the following weather information: temperature, weather condition and wind speed</p>
</li>
<li><p>Error handling</p>
</li>
</ul>
<p>This is a simple website with pretty basic features, and should be relatively easy to build.</p>
<p>Before we start, let’s go over some prerequisites. I assume you are already familiar with the basics of HTML, CSS and JavaScript. Knowing Git would be helpful, but it’s not necessary – you can still follow along with the steps in this article.</p>
<h2 id="heading-how-to-set-up-the-project">How to Set Up the Project</h2>
<p>Let’s begin by setting up the project. To keep things simple, we’ll just use HTML, CSS, and JavaScript to build the website. So, let’s create the following files:</p>
<pre><code class="lang-bash">weather-app/
│── index.html
│── style.css
│── script.js
</code></pre>
<p>Next, to get the weather data, we’ll use an open-source weather API form <a target="_blank" href="https://open-meteo.com">Open-Meteo</a>, since it’s free and doesn’t need an API key. It will provide us with the temperature, wind speed, and weather conditions.</p>
<p>Before we really dive in, make sure that you have Git installed in your system. If you don’t have Git, you can refer to <a target="_blank" href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Git SCM</a> for an installation guide on Mac and Windows. If you are not familiar with Git, then check out the following guides to get started:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-git-in-under-10-minutes-da548267cc91/">Learn the Basics of Git in Under 10 Minutes</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/gitting-things-done-book/">Full book on Git and GitHub + version control basics</a></p>
</li>
<li><p><a target="_blank" href="https://docs.github.com/en/get-started/start-your-journey">Getting Started with GitHub</a></p>
</li>
</ul>
<p>Now you can create and initialise your Git repository. To initialise a local repository, run the following command inside your project directory:</p>
<pre><code class="lang-bash">git init
</code></pre>
<p>Next, go to GitHub and create a new repository with the same name as your project. Refer to the <a target="_blank" href="https://docs.github.com/en/repositories/creating-and-managing-repositories/quickstart-for-repositories">Quickstart guide</a> if you are not familiar with the process. Run the commands shown on the screen once you have created the repository.</p>
<p>Once you’re done with these steps, we are ready to get started on the development process.</p>
<h2 id="heading-how-to-build-the-website">How to Build the Website</h2>
<p>In this phase, we’ll develop or code our website. By looking at the designs and requirements, we’ll decide how to approach the development of each component.</p>
<p>This is a simple, small website with few requirements. So we won’t be using any frameworks, just simple HTML,CSS and JavaScript. But, depending on how complex the requirements are, you may decide to use frameworks like React, Angular, and so on.</p>
<p>First, let’s create a basic layout of the webpage with HTML:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Weather App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"searchContainer"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">class</span>=<span class="hljs-string">"inputField"</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">"cityField"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter city name..."</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"searchBtn"</span>&gt;</span>Search<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"weatherContainer"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cityName"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"temperature"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"condition"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"windSpeed"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"errorMessage"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>We have added the following:</p>
<ul>
<li><p>A search container that will contain our search field with an input to enter city name, and a Search button</p>
</li>
<li><p>Another container that will display the weather information or error message once the user clicks on Search</p>
</li>
</ul>
<p>Next, let’s style it with CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">background</span>: white;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">10px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
  <span class="hljs-attribute">margin</span>: auto;
}

<span class="hljs-selector-class">.searchContainer</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">20px</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.inputField</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.searchBtn</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#007bff</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-id">#weatherContainer</span> {
  <span class="hljs-attribute">display</span>: none; <span class="hljs-comment">/* Hide until data is available to display */</span>
}

<span class="hljs-selector-id">#errorMessage</span> {
  <span class="hljs-attribute">color</span>: red;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p>With HTML and CSS, we have built a static website that looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742722248758/46e8d7d8-c1dd-47d8-9697-03fb9d07229f.png" alt="Rendered Static UI" class="image--center mx-auto" width="1536" height="804" loading="lazy"></p>
<p>Now, let’s add some functionality to it with JavaScript. We’ll be calling the following endpoints:</p>
<ul>
<li><p><code>/v1/search</code> for getting longitude and latitude by city name</p>
</li>
<li><p><code>v1/forecast</code> for getting weather info</p>
</li>
</ul>
<p>First, let’s add an <code>onclick</code> handler to our button:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"searchBtn"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> city = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"cityField"</span>).value.trim();
  <span class="hljs-keyword">if</span> (city) {
    getCoordinates(city);
  } <span class="hljs-keyword">else</span> {
    showError(<span class="hljs-string">"Please enter a city name"</span>);
  }
});
</code></pre>
<p>Clicking on the search button should call the above two APIs, one after the other. Let’s call the first API in the <code>getCoordinates</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCoordinates</span>(<span class="hljs-params">city</span>) </span>{
  showError(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(
      <span class="hljs-string">`https://geocoding-api.open-meteo.com/v1/search?name=<span class="hljs-subst">${city}</span>&amp;count=1`</span>
    );

    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"City not found"</span>);
    }

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">if</span> (!data.results || data.results.length === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Location not found"</span>);
    }

    <span class="hljs-keyword">const</span> { latitude, longitude, name, country } = data.results[<span class="hljs-number">0</span>];
    getWeather(latitude, longitude, name, country);
  } <span class="hljs-keyword">catch</span> (error) {
    showError(error.message);
  }
}
</code></pre>
<p>Here, we call the first API to fetch coordinates, and check if the response is positive. If it isn’t we throw an error and show it in the DOM. If the coordinates are fetched successfully, we move forward and get the weather data for those coordinates:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getWeather</span>(<span class="hljs-params">latitude, longitude, city, country</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(
      <span class="hljs-string">`https://api.open-meteo.com/v1/forecast?latitude=<span class="hljs-subst">${latitude}</span>&amp;longitude=<span class="hljs-subst">${longitude}</span>&amp;current_weather=true`</span>
    );

    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Weather data not available"</span>);
    }

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    displayWeather(data.current_weather, city, country);
  } <span class="hljs-keyword">catch</span> (error) {
    showError(error.message);
  }
}
</code></pre>
<p>Here, again we do the same thing, handle any errors and render the weather data on the screen, inside the <code>displayWeather</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayWeather</span>(<span class="hljs-params">weather, city, country</span>) </span>{
  <span class="hljs-keyword">const</span> weatherContainer = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"weatherContainer"</span>);
  <span class="hljs-keyword">const</span> cityHeader = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"cityName"</span>);
  <span class="hljs-keyword">const</span> temp = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"temperature"</span>);
  <span class="hljs-keyword">const</span> condition = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"condition"</span>);
  <span class="hljs-keyword">const</span> windSpeed = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"windSpeed"</span>);

  <span class="hljs-keyword">const</span> weatherCondition =
    weatherDescriptions[weather.weathercode] || <span class="hljs-string">"Unknown Condition"</span>;

  weatherContainer.style.display = <span class="hljs-string">"block"</span>;
  cityHeader.textContent = <span class="hljs-string">`<span class="hljs-subst">${city}</span>, <span class="hljs-subst">${country}</span>`</span>;
  temp.textContent = <span class="hljs-string">`Temperature: <span class="hljs-subst">${weather.temperature}</span>°C`</span>;
  condition.textContent = <span class="hljs-string">`Condition: <span class="hljs-subst">${weatherCondition}</span>`</span>;
  windSpeed.textContent = <span class="hljs-string">`Wind Speed: <span class="hljs-subst">${weather.windspeed}</span> km/h`</span>;
}
</code></pre>
<p>Next, the <code>showError</code> method contains our error handling logic. It will display any error on the screen.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showError</span>(<span class="hljs-params">message</span>) </span>{
  <span class="hljs-keyword">const</span> weatherContainer = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"weatherContainer"</span>);
  weatherContainer.style.display = <span class="hljs-string">"none"</span>;
  <span class="hljs-keyword">const</span> errorPara = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"errorMessage"</span>);
  errorPara.textContent = message;
}
</code></pre>
<p>Alright, we’re done with the development part! Now it’s time to test our code.</p>
<h2 id="heading-how-to-test-the-code">How to Test the Code</h2>
<p>Whenever you develop a feature, you’ll want to make sure to test it thoroughly. One way to test is by considering all the ways a user might interact with your website. Then, check how your website behaves in each scenario or test case.</p>
<p>First, let's see if the website works as expected when given a valid city name. Enter a city name and click on search – it should display the weather information like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743082937133/ab532ffe-2a48-4101-9d04-7c2eb10d944b.png" alt="Weather Data Visible for Mumbai" class="image--center mx-auto" width="1420" height="858" loading="lazy"></p>
<p>Next, let’s test our error handling, by adding gibberish in the input:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743082992278/8b8629a4-db3a-45b6-87fd-295be4386941.png" alt="Gibberish Input results in Location Not Found" class="image--center mx-auto" width="1240" height="580" loading="lazy"></p>
<p>With this input, our API fails, and returns the above error, which is being displayed correctly.</p>
<p>Remember that our website is really simple, so we don’t have a lot of test cases. But in a real world website, a good practice is to make a list of test cases, and test your website against each of them.</p>
<p>In this context, we are doing functional testing to ensure that the website behaves as expected in different scenarios. This includes testing the core functionalities like searching for a city and handling errors. This type of testing is crucial because it verifies that the application performs its intended functions correctly.</p>
<p>In addition to this, you can perform other types of testing on a website:</p>
<ul>
<li><p>Unit Testing: Testing individual components or pieces of code in isolation</p>
</li>
<li><p>Integration Testing: Testing interactions between different components of the website</p>
</li>
<li><p>End to End Testing: Testing the entire application flow from start to finish</p>
</li>
</ul>
<p>Once you are sure that the website is working as expected, it’s time to push your code to a remote repository like GitHub and release it into production – that is, on the internet.</p>
<h2 id="heading-how-to-push-your-code-to-version-control">How to Push Your Code to Version Control</h2>
<p>Before moving forward, you might be wondering why version control is important. Version control helps you keep track of changes in your code in an organized way. Here are the benefits:</p>
<ul>
<li><p>If something breaks in your code, you can revert back to a previous version if necessary.</p>
</li>
<li><p>Your project is safely stored on GitHub, so you won’t lose progress.</p>
</li>
<li><p>With <a target="_blank" href="https://www.atlassian.com/git/tutorials/using-branches">branches</a>, you can work on different features at the same time, without them interfering with each other, or the main code. This is helpful especially when there are multiple people working on the project.</p>
</li>
<li><p>Deployment and Hosting platforms like Netlify integrate seamlessly with version control systems like GitHub.</p>
</li>
</ul>
<p>Let’s push our code to Github now. Make sure you have run all the commands that are displayed when you create the repository for the first time.</p>
<p>Run the following commands:</p>
<pre><code class="lang-bash">git add .
git commit -m <span class="hljs-string">"Added weather information with API calls"</span>
git push origin main
</code></pre>
<p>The first command adds your changes to the <a target="_blank" href="https://git-scm.com/about/staging-area">staging area</a>. The second one commits your changes locally, while the last one pushes them to the remote repository.</p>
<p>Here, we have pushed the code directly to <code>master</code>. But usually, you will work on a feature in a separate branch and raise a <a target="_blank" href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#">pull request</a> (or merge request), after which your code can be <a target="_blank" href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/merging-a-pull-request">merged</a> into master/main branch.</p>
<p>Now that your code is pushed to GitHub, we’ll move forward to deployment and hosting. you can find the git repo of my code <a target="_blank" href="https://github.com/KunalN25/test-weather-app">here</a>.</p>
<h2 id="heading-deployment-and-hosting">Deployment and Hosting</h2>
<p>Before jumping into these steps, let's first understand what deployment and hosting mean. Simply put, deployment is about taking your website and putting it on the Internet, while hosting services store your website to ensure it is accessible to people online.</p>
<p>We'll use Netlify, a beginner-friendly platform that lets you deploy websites directly from your GitHub repository. It's perfect for deploying simple websites built with HTML, CSS, and JavaScript. You also get a free URL with your website (or you can pay for a domain name).</p>
<p>To get started, first visit <a target="_blank" href="https://www.netlify.com">netlify.com</a>, and sign up with your email or GitHub account. Once logged in, you’ll see a landing page. Click on "Add new site” → “Import an existing project”.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744635933602/b092d758-ceec-4980-a36f-7e2d863ff5b6.png" alt="Netlify Landing Page" class="image--center mx-auto" width="3024" height="1458" loading="lazy"></p>
<p>Then, connect your GitHub account by authorising Netlify to access your GitHub repositories. It will show a list of all your GitHub repositories. Search for your repository <code>test-weather-app</code>, or whatever you named it and select it.</p>
<p>Then, you’ll be greeted with the following page to enter configurations. Since our project does not use any frameworks, we do not need to specify any build commands. So, we leave most of the fields empty and click one “Deploy”.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744635796692/3176dc6c-5f3c-4abf-948f-dda44536dce0.png" alt="Website Config" class="image--center mx-auto" width="3024" height="1682" loading="lazy"></p>
<p>Netlify will deploy your site in a few minutes and will provide you with the link. You can find this example website by visiting the following link:</p>
<p><a target="_blank" href="https://testweatherapp11.netlify.app">https://testweatherapp11.netlify.app</a></p>
<p>Netlify will also give you an option to purchase a custom domain. So, if you aim to build an actual website to profit from, then you can use that option.</p>
<p>If you want to make any changes, Netlify will deploy those automatically when you push them to GitHub.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And just like that, your website is live on the internet. That’s all it took. You just wrote some code on your local machine, built a simple web page from scratch, and now it’s live on the internet for other people to use. How great is that!</p>
<p>Now that you have learned how to build a website from scratch and deploy it to the internet, here are few additional things you should remember:</p>
<ul>
<li><p>Website development is not finished just yet. As you keeping building stuff, your website will grow. You’ll explore different designs, fix bugs, and improve features as per feedback.</p>
</li>
<li><p>As your website grows, you’ll also need to think about website’s performance, with increased usage, and security, to protect yourself and your users from attackers.</p>
</li>
<li><p>I have described a highly simplified process. Usually there’s requirement gathering, creating a website design, and estimations before you even start the development.</p>
</li>
<li><p>You’ll also collaborate with other people such as designers, backend engineers, product managers and stakeholders.</p>
</li>
<li><p>Often, a website is developed in increments, that is a basic version of the website with basic features will be released at first, like we did. Then, for each feature, the whole process starting from the design, through the development and testing to deployment is followed.</p>
</li>
<li><p>To make your website usable for everyone, including people who have various disabilities, you’ll want to follow web accessibility best practices. There are a number of practices that you should follow during the development phase. I have described them in detail in my <a target="_blank" href="https://www.freecodecamp.org/news/the-web-accessibility-handbook/">web accessibility handbook here</a>.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The journey of building a website from scratch and releasing it to the internet is rewarding in many ways. Through this process, you gain valuable web development skills, plus you’ll get better at using version control to keep track of your work. And sharing what you’ve built with the community is so satisfying.</p>
<p>In this tutorial, I have explained a very simplified process, but remember that real-world projects often involve more complexity, including collaboration, performance optimisation, and security considerations.</p>
<p>As you continue to develop your skills, you'll face new challenges and have great opportunities to enhance your website's functionality and user experience. Embrace the learning process, and enjoy the satisfaction of seeing your creation come to life on the internet. Happy coding!</p>
<p>If you have any questions or need further clarification, please don't hesitate to reach out. Your feedback is always valued and appreciated! Connect with me on <a target="_blank" href="https://x.com/i/flow/login?redirect_after_login=%2FKunal_N25">Twitter</a> for more updates and discussions. Thank you for reading, and I look forward to seeing you next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Everything You Need to Know About Web Accessibility ]]>
                </title>
                <description>
                    <![CDATA[ The web is a great place to access information and connect with people. It has opened up countless opportunities, making life more convenient in many ways. But not everyone experiences the web in the same way. Websites are difficult to use for people... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-web-accessibility-handbook/</link>
                <guid isPermaLink="false">67d9aa58a50edbbdc70e2941</guid>
                
                    <category>
                        <![CDATA[ Accessibility ]]>
                    </category>
                
                    <category>
                        <![CDATA[ a11y ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Design ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Tue, 18 Mar 2025 17:16:08 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742318086251/103cec5f-3330-4559-8554-4ec76b16ec76.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The web is a great place to access information and connect with people. It has opened up countless opportunities, making life more convenient in many ways.</p>
<p>But not everyone experiences the web in the same way. Websites are difficult to use for people who have visual, hearing, or mobility impairments. These barriers make it harder to navigate content, and in some cases, make the web completely inaccessible.</p>
<p>This handbook will help you understand accessibility and how to implement it. Whether you are a beginner or an intermediate developer, you'll learn basic accessibility practices and some advanced techniques. This will help you make your website more inclusive.</p>
<p>Let’s get started.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-accessibility">What is Accessibility?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-basic-accessibility-practices">Basic Accessibility Practices</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-semantic-and-non-semantic-html">Semantic and Non-Semantic HTML</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-text-content">Text Content</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-page-layouts">Page Layouts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-interactive-elements">Interactive Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keyboard-accessibility">Keyboard Accessibility</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-form-labels">Form Labels</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-links">Links</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-table-accessibility">Table Accessibility</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-css-and-javascript-practices">Additional CSS and JavaScript Practices</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-styling-form-elements">Styling Form Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-color-contrast">Color Contrast</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript-practices">JavaScript Practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-advanced-accessibility-practices-wai-aria">Advanced Accessibility Practices: WAI-ARIA</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-role-attribute">The role attribute</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-aria--attribute">aria-* attribute</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dynamic-content-attributes">Dynamic Content Attributes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-form-validation-and-errors">Form Validation and Errors</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-non-semantic-elements-as-buttons">Using non-semantic elements as buttons</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-multimedia-accessibility">Multimedia Accessibility</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-mobile-accessibility">Mobile Accessibility</a></p>
</li>
</ul>
<h2 id="heading-what-is-accessibility">What is Accessibility?</h2>
<p>Accessibility (A11y) is an important practice in web development that aims to make the website usable (accessible) for all people. This includes people who have disabilities that make it difficult for them to use websites. By making a website accessible to everyone, including people with disabilities, we ensure that they have the same opportunities as we do. We’re also helping to make the web a more inclusive place overall.</p>
<p>What kind of disabilities should we consider? In broad terms:</p>
<ul>
<li><p>Visual impairments: blindness, blurred vision, and colour blindness</p>
</li>
<li><p>Hearing impairments: low to no hearing</p>
</li>
<li><p>Mobility Impairments: difficulty with physical movement(s)</p>
</li>
<li><p>Cognitive Impairments: like Dyslexia and ADHD</p>
</li>
</ul>
<p>People with visual impairments commonly use devices like <a target="_blank" href="https://axesslab.com/what-is-a-screen-reader/">screen readers</a> to visualise and understand a website’s content, for example. So a big part of web accessibility is designing a website that can be easily accessed by a screen reader.</p>
<p>There are various practices that you, as a developer, can follow to make a website accessible, which I’ll cover in this handbook.</p>
<h2 id="heading-basic-accessibility-practices">Basic Accessibility Practices</h2>
<p>Accessibility is not just an added feature on top of a website you’ve already developed. It is a practice that needs to be followed throughout the development process. Whenever you are creating content on the web page, ask yourself if it is really accessible.</p>
<p>Another important point is that accessibility is not just for people with impairments. It benefits everybody by making a website easier to use, thus improving overall user experience.</p>
<p>How do you achieve good accessibility? Well, there are some practices that you should follow while writing HTML, CSS, and JavaScript code. We’ll discuss some basic practices in this section.</p>
<p>Before we get into it, let’s start by understanding what semantic and non-semantic HTML tags are:</p>
<h3 id="heading-semantic-and-non-semantic-html">Semantic and Non-semantic HTML</h3>
<p>Non-semantic HTML tags do not convey specific meaning or purpose. They can be used for anything, depending on the CSS styling and JavaScript functionality. Examples of non-semantic tags are: <code>&lt;div&gt;</code> and <code>&lt;span&gt;</code>. These tags are mostly used as containers for wrapping other elements.</p>
<p>Semantic HTML tags clearly describe their purpose to the browser and the developers through their names. They improve code readability and also help with <a target="_blank" href="https://seo.co/semantic-html/">SEO (Search Engine Optimisation)</a>. Examples of semantic tags include: <code>&lt;button&gt;</code>, <code>&lt;a&gt;</code>, <code>&lt;header&gt;</code>, <code>&lt;footer&gt;</code>.</p>
<p>You can find a list of all semantic elements <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Semantics#semantic_elements">here</a>.</p>
<h4 id="heading-importance-of-using-semantic-html">Importance of using semantic HTML</h4>
<p>An essential part of accessibility is using the correct HTML element for its intended purpose. This means, for example, using a <code>&lt;button&gt;</code> tag when you want to render a button.</p>
<p>But why use semantic elements? After all, you can use CSS to make a <code>&lt;div&gt;</code> look like a button. True, but using semantic elements is important for the following reasons:</p>
<ul>
<li><p>Semantic elements have built-in styles and functionality that you otherwise would need to add through CSS and JavaScript. This makes them easier to use.</p>
</li>
<li><p>They make the code easier to read and maintain, as you can actually see the elements being used rather than seeing a bunch of divs everywhere.</p>
</li>
<li><p>Screen readers can easily read and interpret semantic elements, helping people with visual impairments.</p>
</li>
</ul>
<p>In the following sections, we’ll understand basic accessibility practices for each type of content you render on HTML. We'll explore how to use the correct HTML tags for each situation, helping you see how choosing the right tag for its purpose improves accessibility.</p>
<p>Feel free to test each example with a screen reader. On Mac, use ⌘+F5 to activate VoiceOver, Mac’s built-in screen reader. For Windows, you can use the built-in screen reader called Narrator by pressing Ctrl + Windows Key + Enter.</p>
<h3 id="heading-text-content">Text Content</h3>
<p>When writing text content, it’s important to use the correct elements for headings, paragraphs, and lists. Let’s understand with the following examples.</p>
<p>Let’s say you write headings and paragraphs in the following way:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"heading1"</span>&gt;</span>Heading 1<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"heading2"</span>&gt;</span>Heading 2<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
This is one paragraph
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
This is another paragraph
</code></pre>
<p>This approach has the following problems:</p>
<ul>
<li><p>The screen reader won’t be able to distinguish between headings and paragraphs – it would just read out the contents in one go, thus confusing people who depend on screen readers.</p>
</li>
<li><p>It’s difficult to style individual paragraphs, since there are no selectors. Even if you add a <code>&lt;span&gt;</code> to each one, it requires extra CSS styling.</p>
</li>
<li><p>It also contains unnecessary line breaks which can be avoided by using the right elements.</p>
</li>
</ul>
<p>The above code is an example of bad semantics. This is what you should do instead:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Heading 1<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Heading 2<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is one paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is another paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here, we have used the right semantic elements for the text content, which has the following benefits:</p>
<ul>
<li><p>A screen reader is able to distinguish the headings from the paragraph text by reading out the heading level before reading the text.</p>
</li>
<li><p><code>h1</code>, <code>h2</code>, and <code>p</code> come with built-in styles and they each render on a new line. This eliminates the need to use line breaks.</p>
</li>
<li><p>The code looks cleaner and is much more readable.</p>
</li>
</ul>
<h4 id="heading-lists">Lists</h4>
<p>To render a list of items, we have the following approaches. The non-semantic approach just groups a bunch of divs together and applies CSS styles to them.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>TODO List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"mylist"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Make Breakfast<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Do Laundry<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Complete blog post<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Again, this achieves the desired output but it’s difficult for screen readers to identify this content as a list of items. Instead, use semantic elements:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>TODO List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"mylist"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Make Breakfast<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Do Laundry<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Complete blog post<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p>This helps screen readers identify the element as an unordered list and read out each item. <code>&lt;ul&gt;</code> also comes with default styles and bullet points for each list item. You can also use <code>&lt;ol/&gt;</code> for numbered lists, where the screen reader reads out the number on each list item.</p>
<p>You can test the above examples with Mac’s VoiceOver to see the difference.</p>
<h4 id="heading-emphasized-text">Emphasized Text</h4>
<p>Emphasized text refers to highlighted text that gives importance to certain words or phrases within a piece of content. When adding emphasized text, it’s important to use the right semantic elements like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong"><code>&lt;strong&gt;</code></a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em"><code>&lt;em&gt;</code></a>.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>For best results, use <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>fresh ingredients<span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span> when cooking.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The process of water turning into gas is called <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>evaporation<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>These elements add some built-in styles to the text like <em>bold</em> and <em>italic</em>. Also, if you test with VoiceOver, you’ll notice that it puts some emphasis on the text inside these elements. This helps people using screen readers identify emphasised text.</p>
<p>You may also add some colour to the emphasized text. But, there’s no need to add a lot of styles, else it may cause confusion. Visit <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Emphasis_and_importance">MDN Docs-Emphasis and Importance</a> to learn more about text emphasis in HTML.</p>
<h4 id="heading-abbreviations">Abbreviations</h4>
<p>Next, when writing abbreviations (or acronyms), it’s a good practice to make them visually different and also include the full expansion of the acronym. You can also add some simple styling to the abbreviation. Learn more about abbreviations in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Advanced_text_features#abbreviations">MDN Docs-Abbreviations</a>.</p>
<h4 id="heading-other-best-practices">Other best practices</h4>
<p>Apart from the above, there are a few other practices that are good to follow:</p>
<ul>
<li><p>Use clear language, wherever possible. For example, expand abbreviations: instead of Jan, write January.</p>
</li>
<li><p>When writing ranges, avoid using dashes if possible, write 1 to 5 instead of 1-5.</p>
</li>
<li><p>Avoid using characters that may confuse users when a screen reader reads them out, for example <code>~</code> or <code>*</code>.</p>
</li>
<li><p>Avoid excessive exclamations and emojis.</p>
</li>
</ul>
<p>Also, when writing CSS for text content, remember these practices:</p>
<ul>
<li><p>When using styles like font sizes, line height, and letter spacing, ensure that the text is comfortable to read.</p>
</li>
<li><p>Your headings should stand out from the other text, in case you are using CSS styles. Usually, this is achieved by just using the right heading tags.</p>
</li>
<li><p>Text color should have 4.5:1 contrast with the background. See the <a class="post-section-overview" href="#heading-color-contrast">Color Contrast</a> section for details.</p>
</li>
</ul>
<p>If you want more tips on styling text, visit <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Text_styling">MDN Docs - CSS Text Styling</a>.</p>
<h3 id="heading-page-layouts">Page Layouts</h3>
<p>Page layout is concerned with how the content is laid out on the screen. When you start designing a web page, your first thought is how your content should be positioned on the screen.</p>
<p>Typically, a web page consists of a header, nav bar, footer, main content, and sidebar. In the <em>bad old days</em> (phrase borrowed from the docs, sorry), developers used tables to create page layouts consisting of these elements.</p>
<p>But tables made the layouts incredibly complex and hard to maintain. Table layouts are also difficult for screen readers to read, affecting accessibility.</p>
<p>Nowadays, there are much better ways to write page layouts. If you are including a header, nav bar, and footer along with the main content, you can use the following semantic elements:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- main navigation in here --&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Here is our page's main content --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- Main content here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">footer</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- footer content in here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">footer</span>&gt;</span>
</code></pre>
<p>Let’s understand each tag used above (skip if you already know):</p>
<ul>
<li><p><code>&lt;header&gt;</code>: Represents the introductory section of a webpage, typically containing headings, logos, or navigation links.</p>
</li>
<li><p><code>&lt;nav&gt;</code>: Defines a navigation section that contains links to other parts of the website or page, providing easy access to important sections.</p>
</li>
<li><p><code>&lt;main&gt;</code>: Represents the main content area that focusses on the primary purpose of the page or the website, excluding common elements like header, footer, or sidebar (may include sidebar depending on the website).</p>
</li>
<li><p><code>&lt;footer&gt;</code>: Represents the bottom section of the web page, typically containing metadata, copyright information, or links to related resources.</p>
</li>
</ul>
<p>These elements are called <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element#content_sectioning">sectioning elements</a>. Following are advantages of using these elements:</p>
<ul>
<li><p>The layout is clear with each element clearly describing its purpose, making the code readable and maintainable.</p>
</li>
<li><p>Using the right semantic elements makes screen readers identify each part of the layout, thus helping visually impaired users understand how the website is structured.</p>
</li>
</ul>
<p>Of course, you can write the above layouts by using divs, but sectioning elements provide good semantics and help users understand the type of content they are navigating.</p>
<h3 id="heading-interactive-elements">Interactive Elements</h3>
<p>These consist of elements through which a user interacts with the web page. These elements include buttons, form fields, links, and so on.</p>
<h4 id="heading-keyboard-accessibility">Keyboard Accessibility</h4>
<p>Each interactive element on a web page should be navigable through the keyboard. This gives a user flexibility while navigating your website. Keyboard accessibility is really helpful for people with mobility impairments that may struggle to use a mouse.</p>
<p>For instance, visit <a target="_blank" href="https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html">this</a> page and try to navigate to each interactive element by pressing Tab on your keyboard. You can also press Enter/Spacebar to click on a button or a link. This should give you an idea of what a keyboard-accessible website looks like.</p>
<p>For the most part, using the right semantic elements should ensure keyboard accessibility, as they come with built-in functionality. Check out the following example:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
  Visit my blog at 
  <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.freecodecamp.org/news/author/KunalN25/"</span>&gt;</span>freecodecamp.org<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click me again<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your name"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Here, we have used the correct semantic elements for the hyperlink, button, and input element. All these elements can be accessed through Tab and interacted with using Enter/Spacebar. Check out other form-related elements in this <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element#forms">list</a>.</p>
<p>Some people use a <code>div</code> or <code>span</code> and make them look like an anchor tag or a button with CSS styling. But this is bad for accessibility for two reasons:</p>
<ul>
<li><p><code>div</code> and <code>span</code> are not tab-able by default. So, even if you do make a <code>div</code> look like a button, the user cannot navigate to it using the keyboard.</p>
</li>
<li><p>Screen readers won’t be able to identify them as buttons, while in the case of semantic elements, they read these elements out as buttons or links.</p>
</li>
</ul>
<p>But if you absolutely have to use a <code>div</code> to create a clickable element, include the following attributes:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"customButton"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"0"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Here, we have added two attributes, <code>tabindex</code> and <code>role</code>. We’ll understand the <code>role</code> attribute in a later section.</p>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex"><code>tabindex</code></a> attribute takes an integer that specifies the tab order of tab-able elements, instead of the default top to bottom tab order. A positive integer means the element is focussed in an order specified by the attribute’s value.</p>
<p>But using tabindex to change the default tab order is not recommended, as it may cause confusion for keyboard navigators and affect accessibility. And frankly, it’s not necessary.</p>
<p>You should only ever use the following two values:</p>
<ul>
<li><p><code>tabindex=”0”</code> makes an element tab-able which means it can be accessed through a keyboard in the natural tab order.</p>
</li>
<li><p><code>tabindex=”-1”</code> means the element is not reachable via keyboard navigation.</p>
</li>
</ul>
<p>These attributes make the <code>div</code> behave like a button, but there’s a small piece of JS code you still need to add to make the button clickable via Enter/Return:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"customButton"</span>).addEventListener(<span class="hljs-string">"keydown"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (event.key === <span class="hljs-string">"Enter"</span>) {
    <span class="hljs-built_in">document</span>.activeElement.click();
  }
});
</code></pre>
<p>Here, we have added an event listener to the element that listens for the keydown event. If the key pressed is Enter, then it calls the element’s <code>onclick</code> method.</p>
<p>If you are using a non-semantic element as a button, you need to add this extra code to make it work like a button. So, only use it if it's absolutely necessary. Otherwise, it's always better to use the correct semantic element in the first place.</p>
<p>Keyboard Accessibility is important for audio and video controls too. We’ll discuss this in the <a class="post-section-overview" href="#heading-multimedia-accessibility">Multimedia Accessibility</a> section.</p>
<h3 id="heading-form-labels">Form Labels</h3>
<p>A form label is some text that describes what you need to enter in a form field. Adding labels to form fields is a necessary practice since it lets the user know how to fill the form. But using the right semantic elements is important.</p>
<p>You could do the following and still achieve the desired output:</p>
<pre><code class="lang-xml">Enter name: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> /&gt;</span>
</code></pre>
<p>This is not good for screen reader users, as it does not read out what the input field is for. Even if it reads out “Enter name”, the user may not associate it with the input field. Instead, use the <code>&lt;label&gt;</code> element for form labels.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Enter name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"nameField"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The <code>for</code> attribute associates the label with the input field. With this, when the screen reader’s focus is on the input field, it reads out the label, followed by “edit field” to let the user know they should enter their name in the input field.</p>
<p>Check out the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/html/good-form.html">form with the label</a> and <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/html/bad-form.html">form without the label</a> in these examples for more clarity. Use Mac’s Voiceover (⌘+F5) or Windows’ Narrator (Ctrl+Windows+Enter) to see how it reads out the form elements.</p>
<p>Using <code>&lt;label&gt;</code> offers more advantages:</p>
<ul>
<li><p>By linking a <code>&lt;label&gt;</code> to an input field with the <code>for</code> attribute (clickable association), clicking on the label focuses on the input field.</p>
</li>
<li><p>Clickable association with input field helps the user’s select small inputs like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox">checkboxes</a> or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio">radio buttons</a>.</p>
</li>
<li><p>It follows semantic HTML and specifies that the text is being used as a form label.</p>
</li>
</ul>
<p>Lastly, remember that the label text should clearly describe what the user should enter into the field. For examples, “Enter name” or “Enter email”.</p>
<p>This applies to buttons as well. Ensure that button text is descriptive enough to tell the user what they are clicking on. Vague texts like “Click me!” or “Click here!” are not helpful. Examples of descriptive text are “Submit Form” or “Download Report” that give the users a clear idea of the button’s action.</p>
<p>Along with these, links also come under interactive elements. But since there are a lot of examples for Links, I’ll discuss them in their own section now.</p>
<h3 id="heading-links">Links</h3>
<p>Links are a key part of web pages as they allow the user to navigate the website. Links serve different purposes: going to a different page in the same website, going to an external website, or downloading something. In this section, you’ll learn about several practices with links that contribute towards accessibility.</p>
<h4 id="heading-linking-to-external-websites">Linking to External Websites</h4>
<p>When you add a link that lets users open an external website, including the <code>target=_blank</code> attribute opens the link in a new tab.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.wikipedia.org/"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span> Wikipedia <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<p>This is helpful for users as they don’t need to exit the website, saving them from the hassle of navigating back to the website.</p>
<p>Also, if your link opens in a new tab, it’s a good idea to mention it so the screen readers can read it out and help visually impaired users.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.wikipedia.org/"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span> &gt;</span>
Wikipedia (opens in new tab)
<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<p>Similarly, if your link opens a non-HTML file, like a pdf or docx, you should mention it:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"jan-salary-slip.pdf"</span>&gt;</span>
Salary-January (PDF)
<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<p>Alternatively, you can use an icon to indicate a link opening in new tab.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.wikipedia.org/"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
  Wikipedia
  <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"new-tab-icon.png"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Opens in new tab"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width:16px; height:16px; margin-left:5px;"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<p>When using an icon, make sure that you include the alt attribute with description about the image. We’ll understand its purpose in the <a class="post-section-overview" href="#heading-multimedia-accessibility">Multimedia Accessibility</a> section.</p>
<h4 id="heading-skip-links">Skip Links</h4>
<p>A skip link is a link element placed at the top of a page that links directly to the main content of the page. This allows the users to skip the headers and all the navigation menus, and directly jump to the main content of the page. This is helpful on websites where there’s lot of repetitive content on top like menus or banners.</p>
<p>Skip links are especially helpful for people who are visually impaired and who might be using screen readers. These links provide a way to bypass repetitive navigation menus and directly access the main content. This also helps keyboard navigators, thus saving time and enhancing the user experience.</p>
<p>To add a skip link, add an anchor tag at the very top, just under the body tag, and link it to the main content.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#main"</span>&gt;</span>Skip to main content<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Page Title<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"nav-links"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/about"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/blog"</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          <span class="hljs-comment">&lt;!-- other nav links --&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"main"</span>&gt;</span>
      <span class="hljs-comment">&lt;!-- Main Content --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>The skip link is keyboard accessible and is also read out by the screen reader. Clicking on it takes you straight to the main content. Visit <a target="_blank" href="https://webaim.org/">WebAIM</a> and press Tab on your keyboard to see skip links in action.</p>
<h4 id="heading-link-styling">Link Styling</h4>
<p>By default, links created with the anchor tag are visually different from non-link text. This is because the anchor tag has built-in styles like colour, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration">text-decoration</a>, focus-ring (displays when you tab on to the link with the keyboard) and hover effects.</p>
<p>Links should look different from the other text so they’re easily distinguishable. As you saw above, the browser does that for you, so you don’t need to do much. But if you are adding custom styles to the link that fit in better with your theme, you need to follow some best practices:</p>
<ul>
<li><p>Links should have different colors for default, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:visited">visited</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:focus">focus</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:hover">hover</a> states.</p>
</li>
<li><p>Link text color should be different from the non-link text and should have different styling.</p>
</li>
<li><p>Link text color should have a contrast of 3:1 between other text and 4.5:1 contrast between background color. See the <a class="post-section-overview" href="#heading-color-contrast">Color Contrast</a> section for more understanding</p>
</li>
</ul>
<p>An example of custom styling for links is shown below (from the Docs):</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff0000</span>;
}

<span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:hover</span>,
<span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:visited</span>,
<span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#a60000</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
}

<span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:active</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#000000</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#a60000</span>;
}
</code></pre>
<p>With the help of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes">pseudo-classes</a>, this adds different styles for when link is hovered, previously visited, focussed (with the keyboard), or active (when the link is being clicked).</p>
<p>You can experiment with different colors and styles, but don’t remove the <code>cursor: pointer</code> or <code>outline</code> properties. Both are important for people using keyboard navigation.</p>
<p>Remember, links already have built-in styles for all the link states. Only add your own if you want something in line with your website’s theme.</p>
<h4 id="heading-avoid-using-onclick-handlers">Avoid using onclick handlers</h4>
<p>Links are used to navigate to another web page on the same website or navigate to an external website. Specifying the link in the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href">href</a> attribute does this for you without any need to add JavaScript code.</p>
<p>But some people add an <code>onclick</code> attribute to anchor elements, to make them behave like buttons and set <code>href=”#”</code> or <code>href="javascript:void(0)"</code> to avoid page refresh. This causes unexpected behaviour and may lead to the following problems:</p>
<ul>
<li><p>Copying or dragging this link adds an unnecessary <code>#</code> or <code>void(0)</code> to the URL, which does not make sense.</p>
</li>
<li><p>Clicking the link immediately scrolls the page to the top, which may lead to the user losing track of where they were.</p>
</li>
<li><p>If JavaScript is still downloading, clicking the link does nothing and the web page becomes unresponsive.</p>
</li>
</ul>
<p>It is also bad for semantics and accessibility, as people using screen readers may get confused. If you want to add JavaScript functionality on click of an element, just use a <code>&lt;button&gt;</code>. Only use links when navigating to a proper URL.</p>
<h4 id="heading-meaningful-link-text">Meaningful Link Text</h4>
<p>Similar to buttons, when writing link text, keep it meaningful and descriptive and avoid using “Click here” or “Click this”.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
  For more information about accessibility
  <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://developer.mozilla.org/en-US/docs/Web/Accessibility"</span>&gt;</span>
    click here
  <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Instead of the above, do this:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
  For more information about accessibility, visit
  <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://developer.mozilla.org/en-US/docs/Web/Accessibility"</span>&gt;</span>
    MDN Docs - Accessibility
  <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Check out the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/html/good-links.html">Good Links</a> and <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/html/bad-links.html">Bad Links</a> examples from the docs. You can also test them with VoiceOver (⌘+F5).</p>
<h4 id="heading-link-proximity">Link Proximity</h4>
<p>If your web page has a lot of interactive elements like links and buttons, ensure that they are spaced properly to prevent accidental clicks. This helps people with <a target="_blank" href="https://axesslab.com/hand-tremors/">Motor Control Issues</a> that may click on the wrong link.</p>
<p>Using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/margin"><code>margin</code></a> property should be enough to ensure spacing.</p>
<h3 id="heading-table-accessibility">Table Accessibility</h3>
<p>In the page layouts section, we saw that using tables for creating page layouts is an outdated practice. However, tables can still be used if you want to display a large amount of data in tabular form. Incorporating accessibility in tables helps screen readers interpret them and help visually impaired users.</p>
<p>Check out <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Table_accessibility">MDN Docs - Table Accessibility</a> to understand best practices.</p>
<h2 id="heading-additional-css-and-js-practices">Additional CSS and JS Practices</h2>
<p>Most of your accessibility goals should be achieved with HTML alone. But there are certain things to keep in mind when writing CSS and JavaScript to ensure you don't break accessibility.</p>
<h3 id="heading-styling-form-elements">Styling Form Elements</h3>
<p>When styling form elements, remember the following:</p>
<ul>
<li><p>Do not remove the default styles for focus outlines, hover, and disabled state in form elements. You may modify them as per your site design, but they should still be visible.</p>
</li>
<li><p>Ensure that your labels and placeholder texts are visually clear. Follow colour contrast practices (next section).</p>
</li>
<li><p>For clickable areas like buttons and inputs, ensure they are large enough so the user can click comfortably.</p>
</li>
<li><p>Success and Error messages should be physically distinguishable from labels and other text content.</p>
</li>
</ul>
<h3 id="heading-color-contrast">Color Contrast</h3>
<p>When you choose colors for your website, your text and background colour should have a good colour contrast. A good color contrast ensures that the text is easily readable by all users (and it also helps people with color blindness in particular).</p>
<p>The WCAG (Web Content Accessibility Guidelines) recommends the following contrast ratios:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736175276741/40ee7fe4-110c-4dd1-95f3-4cb7620de032.png" alt="Recommended Color contrast ratios" class="image--center mx-auto" width="1566" height="498" loading="lazy"></p>
<p>Let’s understand the colour contrast ratings:</p>
<ul>
<li><p>AA rating refers to the minimum ratio your colour contrast should be such that the site’s content is readable. As you can see in the table above, this requires a 4.5:1 minimum ratio for body text, a 3:1 ratio for large-scale text, and a 3:1 ratio for active user interface components and graphical objects.</p>
</li>
<li><p>AAA rating is the ideal standard for accessibility that ensures high contrast for your website. This requires a 7:1 ratio for body text, a 4.5:1 ratio for large-scale text, and isn’t defined for UI components/graphical objects.</p>
</li>
</ul>
<p>Choose a contrast ratio that aligns well with your design, but try to keep it to at least AA rating. To check colour contrast ratio between two colors, you can use the following tools:</p>
<ul>
<li><p><a target="_blank" href="https://webaim.org/resources/contrastchecker/">Color Contrast Checker</a></p>
</li>
<li><p><a target="_blank" href="https://developer.chrome.com/docs/devtools/accessibility/contrast">Chrome Developer Tools</a> - Identifies text in your website not meeting AA and AAA ratings</p>
</li>
</ul>
<h3 id="heading-javascript-practices">JavaScript Practices</h3>
<h4 id="heading-mouse-specific-events">Mouse-specific events</h4>
<p>When you have functionality triggered by events like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event">mouse-over</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseout_event">mouse-out</a>, they cannot be accessed by people that depend on keyboard navigation. So, to make the functionality accessible by keyboard, you need to add the same event handlers to events like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/focus_event">focus</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event">blur</a>.</p>
<h4 id="heading-client-side-form-validations">Client side form validations</h4>
<p>When you submit data through a form, the data is validated to check if you have entered valid data. Often, when the data is sent to the server, the server validates the data and lets the UI know if the validation has failed.</p>
<p>To make the website user-friendly, it helps to add form validations on the client-side, so users can get instant feedback if they have entered incorrect data, since the server-side mechanism may take time. This is a very small step towards improving user experience.</p>
<p>Check out the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/css/form-validation.html">Form Validation</a> Example to understand more.</p>
<p>Apart from the above, one thing you should remember is not to use JavaScript for anything and everything. JavaScript can be used to generate any form of HTML and dynamically apply CSS styling. It is very helpful if you have dynamic content on your website.</p>
<p>But if you have too much HTML generated by JavaScript, it gets hard for screen readers to keep track of the dynamic changes. This makes the website difficult to read for impaired users. So, make sure you don't overuse JavaScript when simple HTML would be enough.</p>
<p>Accessibility for dynamic content updates is covered in the next section.</p>
<h2 id="heading-advanced-accessibility-practices-wai-aria">Advanced Accessibility Practices: WAI-ARIA</h2>
<p>As applications started to get bigger and more complex, developers started needing a new set of accessibility features. Semantic elements alone were not enough, especially for complex elements like date pickers and custom widgets.</p>
<p>Depending on semantic HTML does not help when content is updated dynamically on the web page. Nowadays, all websites built with JavaScript have content that isn’t loaded initially, but updated dynamically based on user interactions.</p>
<p>WAI-ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications) was introduced to add more accessibility features wherever they were needed. It defines a set of HTML attributes that you can use to provide additional semantics to your website and improve accessibility.</p>
<p>In the following sections, you’ll learn which attributes were introduced and how you can use them to enhance accessibility.</p>
<h3 id="heading-the-role-attribute">The <code>role</code> attribute</h3>
<p>The <code>role</code> attribute helps add semantic information to non-semantic elements by defining their “role” on the web page. With roles, screen readers can accurately read non-semantic elements and help identify them for people with disabilities.</p>
<p>W3C defines several roles that you can use, depending on their purpose. But keep in mind that you should only use <code>role</code> when necessary. In most cases, it’s better to just use the right semantic elements like <code>&lt;button&gt;</code>, <code>&lt;nav&gt;</code>, <code>&lt;header&gt;</code>, and so on.</p>
<p>But, when semantic elements are not fulfilling your purpose, roles can help. So, let’s understand how to use them with some examples:</p>
<p>If you want to create a button with custom <code>div</code>, adding the <code>role</code> attribute specifies that this element is being used as a button.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"0"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>When you test this with Mac’s VoiceOver (⌘+F5), it reads out the element as a button. As discussed before, always include the <code>tabindex</code> attribute.</p>
<p>But if you want to use a <code>div</code> instead of a button, you still need to add JavaScript functionality, as explained in the the <a class="post-section-overview" href="#heading-keyboard-accessibility">Keyboard Accessibility</a> section.</p>
<p>Another example is if you are writing a custom link. You can use the following role, so that the screen reader interprets this as a link:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"link"</span>&gt;</span>Visit our website<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Apart from interactive elements, <code>role</code> attribute can also be used to define elements as navigation menus, side bars, banners, etc. If you are using non-semantic elements for these purposes, always include a role, like the following:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"navigation"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Navigation menu items --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In this case, the screen reader announces this as a navigation area.</p>
<p>Also, if you have an element that serves as an alert for the user, including the following role makes the screen reader announce it as soon as it shows up on the screen, even if it doesn’t have focus:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"alert"</span>&gt;</span>
  Please respond to this alert
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>You can find the full list of available roles at <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles">MDN Docs: WAI-ARIA Roles</a>.</p>
<h3 id="heading-aria-attributes">aria-* attributes</h3>
<p>Apart from <code>role</code>, ARIA (Accessible Rich Internet Applications) defines extra attributes to enhance the accessibility of web applications. These attributes give screen readers more information about elements, helping people with disabilities better understand them.</p>
<p>If native semantic elements or the <code>role</code> attribute alone are not sufficient, aria-* attributes can provide extra context. You can find a full list of these attributes in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes">MDN Docs-ARIA</a>.</p>
<p>In the following sections, we’ll see how role and aria-* attributes can improve accessibility. We won’t cover all the attributes here, but we’ll focus on the most commonly used ones.</p>
<h3 id="heading-dynamic-content-updates">Dynamic Content Updates</h3>
<p>When a web page loads for the first time, its content is read out by the screen reader. But screen readers cannot capture dynamic content, that is content that gets added or removed.</p>
<p>For example, when a web page is showing live sport updates, it gets updated almost every minute. Screen readers will only read out the content displayed when the page is first rendered, but don’t show dynamic updates.</p>
<p>This is not really a problem for many users, but for people with visual impairments, screen readers may not be able to read the changes on the page. Most modern websites are dynamic in nature, so it’s important to consider accessibility of dynamic content updates.</p>
<p>Check out the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/aria/aria-no-live.html">aria-no-live</a> example from MDN Docs. It loads a new quote every 10 seconds, which you can see clearly as a user with no visual impairment. But the screen reader only reads the initial page content and does not announce the updates. This is not good for accessibility.</p>
<p>To fix this, WAI-ARIA provides the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live"><code>aria-live</code></a> attribute that makes the screen reader read out content that is updated. You can add this attribute to the element that contains the dynamic content.</p>
<p>It takes the following three values:</p>
<ul>
<li><p><code>aria-live="off"</code>: Default value that means no content is read out</p>
</li>
<li><p><code>aria-live="polite"</code> Updates only announced when the user is idle</p>
</li>
<li><p><code>aria-live="assertive"</code>: Content read out as soon as it is updated.</p>
</li>
</ul>
<p>Depending on the importance of the update, you can decide which value to use.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">aria-live</span>=<span class="hljs-string">"polite"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Dynamic Content here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In this case, the screen reader waits till the user is done with their current task before announcing the update.</p>
<p>You can add more detail here. With the above attribute, only the text that is updated is read out. But, screen reader users may get confused as to which part of the page is being read out. So, it is helpful if the entire element is read out.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">aria-live</span>=<span class="hljs-string">"assertive"</span> <span class="hljs-attr">aria-atomic</span>=<span class="hljs-string">"true"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Dynamic Content here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic"><code>aria-atomic</code></a> attribute tells screen readers to read out the entire element as a single atomic unit. This avoids confusion for visually impaired users. Check out the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/aria/aria-live.html">aria-live</a> example from MDN Docs with Mac’s VoiceOver (⌘+F5). It reads out the entire element when the content is updated.</p>
<h3 id="heading-form-validation-and-errors">Form Validation and Errors</h3>
<p>Let’s say you have added some validation to your form through JavaScript. When the validation fails, an error message gets added on the screen. For example, a required message shows up if you have missed a field.</p>
<p>The implementation for error handling involves creating an element containing an error message or a list of errors that render on certain conditions, depending on the JavaScript code. Just as we discussed in the previous section, the screen reader does not read out new content updates.</p>
<p>So, we should make sure that the screen reader reads out the error message as soon as it shows up, to let visually impaired users know that an error has been thrown. We can use the following attributes for this purpose:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"errors"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"alert"</span> <span class="hljs-attr">aria-relevant</span>=<span class="hljs-string">"all"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role"><code>alert</code></a> role does two things. It semantically identifies this element as a piece of important information. Secondly, this role turns the element into a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">live</a> region which means the screen reader is notified immediately if there are any changes.</p>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant"><code>aria-relevant</code></a> attribute describes what changes need to be announced in a live region. The attribute takes a space-separated list of the following values:</p>
<ul>
<li><p><code>additions</code>: Announces new content added to the live region</p>
</li>
<li><p><code>removals</code>: Content removed from the live region is read out</p>
</li>
<li><p><code>text</code>: Announces any modifications to existing content.</p>
</li>
</ul>
<p>It also takes a value <code>all</code> which is a shorthand for <code>additions removals text</code>, meaning all three types of content are read out.</p>
<p>You can check the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/css/form-validation.html">Form Validation Example</a> from the MDN Docs.</p>
<p>Next, let’s see what to do if we want to mark certain fields as required. Normally, we’d add visual cues like a <code>*</code> and the following message at the top of the form:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fields marked with an asterisk (*) are required.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This is helpful for regular users, but visually impaired users may get confused as to which fields are required. To make it easier for them, we can use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required"><code>aria-required</code></a> attribute.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">aria-required</span>=<span class="hljs-string">"true"</span> /&gt;</span>
</code></pre>
<p>With this attribute, the screen reader mentions this field as “required” while reading it out.</p>
<p>When you are creating input fields, it’s important to include a label, as some screen readers do not read out placeholder text. If you don’t want to include a label field, here are the following alternatives:</p>
<p>You can use the <code>aria-label</code> attribute to add labels to input fields that do not have a label associated with them.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"Enter email"</span> /&gt;</span>
</code></pre>
<p>This attribute provides some text to be read out by a screen reader to describe the input field.</p>
<p>You can go one step further and use the <code>aria-labelledby</code> attribute that uses another element to act as a label for the input field. For example:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"emailLabel"</span>&gt;</span>Enter your email<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">aria-labelledby</span>=<span class="hljs-string">"emailLabel"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The screen reader reads out the text inside the <code>&lt;span&gt;</code> element to describe the input element. This is similar to having a <code>&lt;label&gt;</code> with a <code>for</code> attribute. You can also use this attribute to reference other interactive elements like <code>&lt;button&gt;</code> or <code>&lt;a&gt;</code> that do not have a label field to reference them.</p>
<p>Keep in mind that the <code>aria-labelledby</code> attribute only defines an accessible name for the element – it does not provide other functionality like clicking on the label to focus on the input element. It’s better to use <code>&lt;label&gt;</code> with a <code>for</code> attribute.</p>
<p>We have already discussed form labels in the <a class="post-section-overview" href="#heading-interactive-elements">Interactive Elements</a> section.</p>
<p>You’ve now seen some of the different attributes that WAI-ARIA offers and how they enhance accessibility. You can visit <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/WAI-ARIA_basics#accessibility_of_non-semantic_controls_2">MDN Docs: WAI-ARIA</a> to check out additional details I may have missed.</p>
<p>Before we move on, remember one thing: <em>use WAI-ARIA only when necessary</em>. Usually, semantic elements are able to achieve majority of your accessibility goals. Don’t over-use WAI-ARIA as they might end up complicating your code.</p>
<h2 id="heading-multimedia-accessibility">Multimedia Accessibility</h2>
<p>A website’s content is not restricted to text. It also often consists of multimedia content like images, audio, and video. In a lot of cases, multimedia content is easier to understand than text content. While this is true for many users, it poses challenges for users with disabilities.</p>
<p>People with visual impairments cannot see images and people who are deaf or hard of hearing cannot easily interpret audio content. So, as developers, it’s our job to make this type of content accessible for everyone. Let’s understand how to make this possible:</p>
<h3 id="heading-images">Images</h3>
<p>Since people with visual impairments cannot see images, they depend on a screen reader to describe the image. Just writing an <code>img</code> tag with <code>src</code> attribute does not help.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"temple.jpg"</span> /&gt;</span>
</code></pre>
<p>By default, the screen reader reads out the file path or URL of the image. A file name might give some idea of the image, but still does not describe it.</p>
<p>So, it’s helpful to add an <code>alt</code> attribute to an <code>img</code>. The <code>alt</code> attribute provides an alternate text for the image, and its purpose is to describe the image.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span>
  <span class="hljs-attr">src</span>=<span class="hljs-string">"temple.jpg"</span>
  <span class="hljs-attr">alt</span>=<span class="hljs-string">"The Meenakshi Temple, situated in Madurai, a South Indian City is dedicated to goddess Meenakshi, a form of Parvati"</span>
/&gt;</span>
</code></pre>
<p>Here, instead of reading the file path, the screen reader reads out the alternate text – that is, the value of the <code>alt</code> attribute. The alternate text should provide a description of the image to help users understand what it’s conveying. So, instead of just saying “Temple”, the user knows which temple is being depicted in the image.</p>
<p>You can also add extra context to the image with the <code>title</code> attribute.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span>
  <span class="hljs-attr">src</span>=<span class="hljs-string">"temple.jpg"</span>
  <span class="hljs-attr">alt</span>=<span class="hljs-string">"The Meenakshi Temple, situated in Madurai, a South Indian City is dedicated to goddess Meenakshi, a form of Parvati"</span>
  <span class="hljs-attr">title</span>=<span class="hljs-string">"The Meenakshi Temple"</span>
/&gt;</span>
</code></pre>
<p>When focussed on the image, the screen reader reads out the <code>alt</code> text and the title.</p>
<p>Let’s take another example which uses an alternative to the <code>alt</code> attribute:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"temple.jpg"</span> <span class="hljs-attr">aria-labelledby</span>=<span class="hljs-string">"temple-label"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"temple-label"</span>&gt;</span>
  The Meenakshi Temple, situated in Madurai, a South Indian City is dedicated to
  goddess Meenakshi, a form of Parvati
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here, instead of using the <code>alt</code> attribute, we have used the <code>aria-labelledby</code> attribute to link the paragraph element to the image. The text inside <code>p</code> acts as an alternate text for the image. This is helpful if you need to use the same text as an alternate text for different images.</p>
<p>Sometimes, we use images as icons for headers and navigation menus, just for decoration. Usually, these images are not relevant to understand the content of the page. In these cases, you add an empty <code>alt</code> attribute.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"page-icon.png"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
  History of Meenakshi Temple 
<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
</code></pre>
<p>If you skip the <code>alt</code> attribute, the screen reader reads out the entire image URL. To avoid this, use an empty <code>alt</code> attribute, so the screen reader simply announces it as an image and moves on, preventing unnecessary distractions for users.</p>
<p>You can also use <code>role=”presentation”</code> to skip reading the image path or alternative text.</p>
<h3 id="heading-audio-and-video">Audio and video</h3>
<p>When using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio">&lt;audio&gt;</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video">&lt;video&gt;</a> elements, remember to include multiple sources – that is, provide the audio and video in different formats. For browsers that do not support the formats you have mentioned, include a fallback download link so they can access the resource.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">audio</span> <span class="hljs-attr">controls</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"audio.mp3"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"audio/mpeg"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"audio.ogg"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"audio/ogg"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    Your browser doesn't support HTML video. Here is a
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"video.mp3"</span>&gt;</span>link to the video<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> instead.
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">audio</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">controls</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"video.mp4"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"video/mp4"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"video.webm"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"video/webm"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    Your browser doesn't support HTML5 video. Here is a
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"video.mp4"</span>&gt;</span>link to the video<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> instead.
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
</code></pre>
<p>Next, let’s understand the shortcomings of using native HTML controls for audio and video.</p>
<ul>
<li><p>They cannot be styled with CSS, so they may not align with your website’s theme.</p>
</li>
<li><p>The play/pause buttons are not keyboard accessible.</p>
</li>
<li><p>They don’t have functionality to forward or rewind the video.</p>
</li>
</ul>
<p>To overcome these limitations, we’ll create our custom video player in the next steps. To start, let’s create a container for the video content:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"controls"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"play-pause"</span>&gt;</span>Play<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"stop"</span>&gt;</span>Reset Video<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>These will work as the play/pause and reset buttons. Then, let’s remove the <code>controls</code> attribute from the <code>&lt;video&gt;</code> to replace them with our custom controls.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> videoPlayer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"video"</span>);
videoPlayer.removeAttribute(<span class="hljs-string">"controls"</span>);
</code></pre>
<p>Why do we remove it at run time? Let’s say JavaScript does not load due to some issue. In this case, the user can still use the native controls. Next, let’s add some functionality to our buttons:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> playPauseBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".play-pause"</span>);
<span class="hljs-keyword">const</span> resetBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".reset"</span>);

playPauseBtn.onclick = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (videoPlayer.paused) {
    videoPlayer.play();
    playPauseBtn.textContent = <span class="hljs-string">"Pause"</span>;
  } <span class="hljs-keyword">else</span> {
    videoPlayer.pause();
    playPauseBtn.textContent = <span class="hljs-string">"Play"</span>;
  }
};

resetBtn.onclick = <span class="hljs-function">() =&gt;</span> {
  videoPlayer.pause();
  videoPlayer.currentTime = <span class="hljs-number">0</span>;
  playPauseBtn.textContent = <span class="hljs-string">"Play"</span>;
};
</code></pre>
<ul>
<li><p>The video player object is of type <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement"><code>HTMLMediaElement</code></a>, that contains several methods you can use to control the video.</p>
</li>
<li><p>For the play/pause button, we add a toggling functionality, with the <code>play()</code> and <code>pause()</code> methods.</p>
</li>
<li><p>To reset the video, we pause it and set the current time to 0.</p>
</li>
</ul>
<p>Now, our custom video player is keyboard accessible, and able to be styled with CSS. You can also add additional functionality like forward/rewind, a timer, and a progress bar. The steps are similar for a custom audio player.</p>
<p>Check out the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/Multimedia#creating_custom_audio_and_video_controls">MDN Docs</a> for more detail about this functionality.</p>
<h4 id="heading-audio-transcripts">Audio Transcripts</h4>
<p>People who are deaf or hard of hearing cannot easily access audio content. So to make it accessible, you need to add transcripts under any audio or video form of content.</p>
<p>If you run a business, you could pay a professional to do the transcripts. Check out the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/Multimedia#audio_transcripts">docs</a> for options. To show the transcript on the UI, you could use a show/hide panel. Referring to the docs, see the <a target="_blank" href="https://mdn.github.io/learning-area/accessibility/multimedia/audio-transcript-ui/">audio transcript UI</a> (<a target="_blank" href="https://github.com/mdn/learning-area/tree/main/accessibility/multimedia/audio-transcript-ui">source code</a>) for an example.</p>
<p>If the audio is a recording of some presentation, you should attach links to any documents or presentation decks. Also, include a description for any visual content being referenced.</p>
<h4 id="heading-video-closed-captioning-and-subtitles">Video Closed Captioning and Subtitles</h4>
<p>First, let’s understand the difference between captions and subtitles. They are implemented in a similar way and visually, they look the same – but their purposes are different.</p>
<p>Captions denote who’s speaking and describe other sound effects in the video. They are mostly added with people who are deaf or hard of hearing in mind. Subtitles help people who don’t understand the language being spoken in the video, by translating it to text that uses the language of their choice.</p>
<p>Let’s see how to add subtitles to your videos. We write subtitles in WebVTT, a format that contains text along with the range of timestamps indicating which text you want in each part of the video. Following is an example of a subtitles file:</p>
<pre><code class="lang-javascript">WEBVTT

<span class="hljs-number">1</span>
<span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">01.230</span> --&gt; <span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">02.606</span>
This is the first subtitle.

<span class="hljs-number">2</span>
<span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">04.739</span> --&gt; <span class="hljs-number">00</span>:<span class="hljs-number">00</span>:<span class="hljs-number">06.074</span>
This is the second.
</code></pre>
<p>Save this file and name it with a <code>.vtt</code> extension. To link this file to your video, include it in a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track"><code>&lt;track&gt;</code></a> element:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">controls</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"video.mp4"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"video/mp4"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">track</span>
    <span class="hljs-attr">src</span>=<span class="hljs-string">"captions.vtt"</span>
    <span class="hljs-attr">kind</span>=<span class="hljs-string">"subtitles"</span>
    <span class="hljs-attr">srclang</span>=<span class="hljs-string">"en"</span>
    <span class="hljs-attr">label</span>=<span class="hljs-string">"English"</span>
    <span class="hljs-attr">default</span>
  /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
</code></pre>
<p>You should include the <code>&lt;track&gt;</code> element inside the <code>&lt;video&gt;</code> element and placed after all the sources. It has the following attributes:</p>
<ul>
<li><p><code>kind</code> mentions the type of file being referenced.</p>
</li>
<li><p><code>srclang</code> indicates the language the subtitles are in.</p>
</li>
<li><p><code>label</code> indicates the text that is shown while the user is selecting a language</p>
</li>
<li><p><code>src</code> is the path or URL of the subtitles file, that is the <code>.vtt</code> file we created previously.</p>
</li>
</ul>
<p>This will show subtitles for the specified timestamps. This will not only help people with hearing impairments, but is also useful for people who don’t understand the language, or those who are working in a noisy environment.</p>
<p>For people who are visually impaired, you could also include text that describes certain visuals in parts of the video. This text would be read out by screen reader.</p>
<p>You can also add custom styling to subtitle menu and subtitle text. Check out <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video">MDN Docs - Adding captions and subtitles to HTML video</a> for the implementation.</p>
<h2 id="heading-mobile-accessibility">Mobile Accessibility</h2>
<p>We have covered many key accessibility practices so far, and they should work well on mobile phones as well. But there are some additional considerations you can follow for mobile users.</p>
<p>First, let’s talk about mouse-specific events. We have already seen how to make mouse-specific events accessible in the <a class="post-section-overview" href="#heading-javascript-practices">JavaScript Practices</a> section. Events like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mousedown_event">mousedown</a> or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseup_event">mouseup</a> are often used for drag and drop functionalities.</p>
<p>But these are not accessible for touchscreen users, so you should add the same functionality to touch-specific events like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event">touchstart</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/touchend_event">touchend</a>. The following example is in the context of drag and drop:</p>
<pre><code class="lang-javascript">source.ontouchstart = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-comment">// initiate drag</span>
};

dest.ontouchend = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
   <span class="hljs-comment">// drop</span>
};
</code></pre>
<p>Next, you have to ensure that you are following responsive design when designing your web pages. Responsive designs make sure the website looks good on both desktop and mobile phones. I have written a detailed guide on <a target="_blank" href="https://medium.com/gitconnected/read-this-to-make-your-website-responsive-35af4ab7992b">responsive design</a>, so check it out if you are interested.</p>
<p>Some other mobile accessibility practices that are good to know:</p>
<ul>
<li><p>Do not disable zoom on your website. Both fully-sighted users as well as those who have visual impairments may need to zoom in to read the website’s content on smaller screens.</p>
</li>
<li><p>When writing navigation menus, you’d normally conceal it and provide a hamburger icon to open it, as the screen is much shorter/smaller on a mobile phone. In these cases, the hamburger menu should be easily accessible. Check out the example of a <a target="_blank" href="https://fritz-weisshart.de/meg_men/">good hamburger menu</a> from the docs, in mobile view.</p>
</li>
<li><p>When creating forms, try to minimise the amount of typing the user needs to do, as it can get annoying for mobile users. This is especially important if your website is primarily designed for mobile users. Check out the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/Mobile#user_input">docs</a> for examples.</p>
</li>
</ul>
<p>Visit <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/Mobile">MDN Docs-Mobile Accessibility</a> if you want to learn more.</p>
<h2 id="heading-testing-accessibility-with-tools">Testing Accessibility with Tools</h2>
<p>There are several tools you can use to test the accessibility of your page. <a target="_blank" href="https://developer.chrome.com/docs/lighthouse/overview">Lighthouse</a> in Chrome Developer Tools is an open source tool that analyses a web page for performance, accessibility, SEO, and more. It generates a report on how a page performs in these areas.</p>
<p>Let’s see how it helps in analysing the accessibility of a page:</p>
<p>Open Chrome Dev Tools and navigate to the Lighthouse tab. Click on “Analyse Page Load” and wait for a few seconds. It will show a report that contains info on how your web page scored on Accessibility and other metrics. It will list down any accessibility issues you may have.</p>
<p>Let’s take the following example:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"2"</span>&gt;</span>Click Here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('Clicked!')"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>When tested with the Lighthouse audit, it yields the following results:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739631885589/c886f304-aba2-44ac-8d75-88fac2f60c55.png" alt="Lighthouse audit with accessibility issues" class="image--center mx-auto" width="3024" height="1794" loading="lazy"></p>
<p>As you can see, it’s scored 74 on accessibility, meaning there is room for improvement. It has also shown the accessibility issues within your HTML code, as you might have guessed looking at the code:</p>
<ul>
<li><p>Image elements do not have <code>alt</code> attribute</p>
</li>
<li><p>Form input does not have a label</p>
</li>
<li><p><code>tabindex</code> value is greater than 0.</p>
</li>
</ul>
<p>Let’s correct these issues and run the test again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739632090527/2db4798a-53d3-4010-9756-83de8b0f208a.png" alt="Lighthouse audit with good accessibility" class="image--center mx-auto" width="3000" height="1774" loading="lazy"></p>
<p>This time, it has scored 100 on Accessibility since we have followed all the basic practices.</p>
<p>As you can see, this is a really simple HTML page, and it’s much harder to achieve a score of 100 for large websites. But, you should aim to achieve as high a score as possible. This shouldn’t be too challenging if you make accessibility a part of your development process.</p>
<p>The accessibility score on it’s own does not mean your website is fully accessible. You also need to test the following:</p>
<ul>
<li><p>Manual testing with a screen reader (Mac’s Voiceover or Windows’ Narrator).</p>
</li>
<li><p>Keyboard accessibility – test whether each and every part of your website is keyboard accessible</p>
</li>
<li><p>Simulating your website with different color contrasts for different visual impairments.</p>
</li>
</ul>
<p>For simulating, Chrome Developer Tools provides a Rendering tool to emulate your website on different preferences, like light/dark mode, high/low color contrast, reduced motion and various visual impairments.</p>
<p>To access it, open Developer Tools, do ⌘+shift+P (Ctrl+Shift+P on Windows) and type “Rendering”. It will open the following window:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1741959781294/36f6c233-9326-4acb-a551-e95a56a87d8a.png" alt="Rendering tool" class="image--center mx-auto" width="1596" height="1484" loading="lazy"></p>
<p>If you have added media queries like the following, you can select these preferences and test whether your website behaves accordingly:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> (prefers-reduced-motion) {
    * {
        <span class="hljs-attribute">animation</span>: none;
    }
}
</code></pre>
<p>So, when you select <code>prefers-reduced-motion</code>, you can test if all the animations have been disabled, and how your website functions.</p>
<p>Apart from the Developer Tools, there’s an NPM plugin called <a target="_blank" href="https://www.npmjs.com/package/eslint-plugin-jsx-a11y">eslint-plugin-jsx-a11y</a> that evaluates React JSX code for accessibility issues.</p>
<p>You can find all the code snippets on <a target="_blank" href="https://github.com/KunalN25/accessibilityguide">GitHub</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Accessibility isn’t just a feature added on top of your code – it should be a part of the development process. When you make a website accessible to everyone, it not only increases your user base, but also promotes inclusivity.</p>
<p>Even though the primary benefactors of accessibility are people with disabilities, it also benefits other users by making the website easier to use overall. A lot of the practices mentioned in the article, like using semantic elements, adding the right attributes, and so on are very easy to follow and go a long way towards ensuring accessibility.</p>
<p>If you are a beginner, you have already done a great job learning about accessibility. Start including simple accessibility practices in your projects. Over time, including these practices will become a natural habit.</p>
<p>I hope this handbook becomes your go-to resource for anything related to accessibility. If you think I've missed something or need clarification on any concepts, feel free to reach out to me on Twitter. For more content on web development, check out out my profile.</p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Accessibility">MDN Docs-Accessibility</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=2oiBKSjOOFE">Web Dev Simplified- Guide on Accessibility</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Become a Web Developer – a Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Are you considering a career in web development? If so, then you are making an excellent choice. Web Development is one of the most in-demand skills in the market in 2024. With over 5.038 billion Internet users, web development has a promising future... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-become-a-web-developer-beginners-guide/</link>
                <guid isPermaLink="false">676884d7626250532f8a0785</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Frontend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2024 21:29:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/505eectW54k/upload/4567a9e14c8e9bac3dc8d6c6a39661f5.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you considering a career in web development? If so, then you are making an excellent choice. Web Development is one of the most in-demand skills in the market in 2024. With over <a target="_blank" href="https://www.webfx.com/web-development/statistics/">5.038 billion Internet users</a>, web development has a promising future.</p>
<p>In this article, I am going to show you the essentials of getting started with web development. We’ll explore key tech stacks, beginner-friendly project ideas, helpful resources, and some additional tips.</p>
<p>Two years ago, I wrote an <a target="_blank" href="https://medium.com/gitconnected/read-this-to-kickstart-your-web-development-journey-26f54b1a4843">article</a> on this topic. Since the demand for web development still remains very high, I am excited to re-visit it with a more detailed guide. So, stick around until the end.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-a-website">What is a Website?</a></p>
<ol>
<li><a class="post-section-overview" href="#heading-frontend-vs-backend-of-a-website">Frontend vs Backend</a></li>
</ol>
</li>
<li><p><a class="post-section-overview" href="#heading-frontend-development">Frontend Development</a></p>
<ol>
<li><p><a class="post-section-overview" href="#heading-html">HTML</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-css">CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript">JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-learn-frontend-frameworks-and-libraries">Frontend Frameworks and Libraries</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-learn-responsive-design">Responsive Design</a></p>
</li>
</ol>
</li>
<li><p><a class="post-section-overview" href="#heading-backend-development">Backend Development</a></p>
<ol>
<li><p><a class="post-section-overview" href="#heading-why-should-you-learn-a-programming-language">Why you should learn a programming language?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-python">Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-golang">Golang</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-java">Java</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript-1">JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-a-programming-language">How to choose a programming language?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-backend-development-frameworks">Backend Frameworks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-databases">Databases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-apis">APIs</a></p>
</li>
</ol>
</li>
<li><p><a class="post-section-overview" href="#heading-git-and-github">Git and GitHub</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-build-a-portfolio-of-projects">Build a portfolio of projects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deployment-and-hosting-platforms">Deployment and Hosting Services</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-tips">Additional Tips</a></p>
</li>
</ol>
<h2 id="heading-what-is-a-website">What is a Website?</h2>
<p>A web page is a document displayed in a web browser (like Chrome, Firefox, and so on). It consists of text, images, and other interactive elements. And a website is a collection of web pages that are connected to each other via links.</p>
<p>A website runs on a remote computer referred to as a web server, and is accessed via the internet. Some examples of well-known websites are Wikipedia, Amazon, and YouTube.</p>
<p><strong>Note</strong>: When I mention web apps or web applications in this article, I mean the same thing as websites.</p>
<p>A web app has two components, the frontend and the backend. Let’s understand the difference between them.</p>
<h3 id="heading-frontend-vs-backend-of-a-website">Frontend vs Backend of a Website</h3>
<p>The frontend is the user interface (UI) of the website, which is basically what the user sees on their screen.</p>
<p>The backend refers to the server where the main logic of the website is located. It also includes the database, where all the application’s data is stored.</p>
<p>The frontend and the backend communicate by exchanging data. Let’s take an example of a social media app like Instagram.</p>
<p>When you upload a post, the UI sends the post data to the backend, which processes the data and adds it to the database. Then the next time, when you load the site/app, it fetches all your posts from the backend and displays them on the screen.</p>
<p>In the next two sections, I will show how you can start with frontend and backend development.</p>
<h2 id="heading-frontend-development">Frontend Development</h2>
<p>As I mentioned above, frontend development is mainly concerned with the UI – that is, the appearance of the website. To get started with frontend development, you’ll need to learn the following three essentials tools:</p>
<h3 id="heading-html">HTML</h3>
<p>HTML (HyperText Markup Language) is used to write web pages that are displayed by the browser. It defines the structure and content of a web page, making it the backbone of every website.</p>
<p>The content of a web page includes elements such as headings, paragraphs, links, images, lists, and so on. HTML creates and structures all these elements through the use of HTML <em>tags.</em> The browser, in turn, interprets this HTML code and renders it on your screen.</p>
<p>freeCodeCamp’s Responsive Web Design certification in their free curriculum starts off by teaching you HTML basics. You’ll even build your own photo app. So that’s a good place to start and dig deep into HTML.</p>
<p>If you want additional practice, <a target="_blank" href="https://www.w3schools.com/html/">w3schools.com</a> is a helpful resource for beginners as well. It offers clear and step-by-step tutorials for each concept. They also provide an interactive editor for you to practice using HTML tags and see the output web page (as does freeCodeCamp).</p>
<p>Focus on the following areas:</p>
<ul>
<li><p>Creating a simple web page</p>
</li>
<li><p>Using HTML tags to render content</p>
</li>
<li><p>Creating Forms</p>
</li>
</ul>
<h3 id="heading-css">CSS</h3>
<p>While HTML defines the structure of the web page, it is not enough as it just creates a skeletal UI of a web page. It just defines what elements are present on the page, and not how they look.</p>
<p>CSS (Cascading Style Sheets) is used to add visual appeal to the web page. It transforms a simple, plain web page into a properly designed user interface.</p>
<p>Here’s how a website looks with plain HTML:</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*SUE5ynYY1Tu5BXOQZCoJtQ.png" alt="1*SUE5ynYY1Tu5BXOQZCoJtQ" width="1400" height="734" loading="lazy"></p>
<p>And this is what it looks like when you add CSS:</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*9cVIjOqY-sQESGI9qDVw0w.png" alt="1*9cVIjOqY-sQESGI9qDVw0w" width="1400" height="749" loading="lazy"></p>
<p>Much better, right? It actually looks like a proper web page, as compared to the skeletal UI before. This is referred to as “styling” a web page.</p>
<p>CSS styling includes the following:</p>
<ul>
<li><p>Colours, fonts, and element backgrounds</p>
</li>
<li><p>Organising content in various layouts (grid, flex box, and so on)</p>
</li>
<li><p>Spacing, that is margins and paddings</p>
</li>
<li><p>Transitions and Animations (Advanced stuff)</p>
</li>
</ul>
<p>As you continue on in the freeCodeCamp curriculum, you’ll learn CSS as well – so that’s a great way to go.</p>
<p>You can also refer to <a target="_blank" href="https://www.w3schools.com/css/default.asp">w3schools.com</a> for CSS Tutorials. Play around with each CSS property in their interactive editors.</p>
<p><strong>Note:</strong> HTML and CSS are NOT programming languages.</p>
<h3 id="heading-javascript">JavaScript</h3>
<p>HTML and CSS are only able to create static websites – that is, you cannot interact with any of the elements on a web page created with just HTML and CSS. The website does not update or respond to any user interactions like button clicks or dropdown selections.</p>
<p>JavaScript (JS) is a programming language that makes a website dynamic and interactive. It adds the following functionalities to a website:</p>
<ul>
<li><p>Handling user interactions like clicks, hovers, keyboard presses, form filling, and so on.</p>
</li>
<li><p>Updating content dynamically on a web page</p>
</li>
<li><p>Handling form validations and submissions</p>
</li>
<li><p>Interacting with the backend servers</p>
</li>
</ul>
<p>JavaScript has many more capabilities that make your website functional and engaging for end users. As you start your JS learning journey, building strong foundation of the concepts is key. Initially, focus on the following areas:</p>
<ul>
<li><p>Basic JavaScript syntax</p>
</li>
<li><p>JS Functions</p>
</li>
<li><p>Interacting with DOM (Document Object Model)</p>
</li>
<li><p>Event Handling</p>
</li>
<li><p>JS Objects and Arrays</p>
</li>
<li><p>Asynchronous JavaScript</p>
</li>
</ul>
<p>Refer to the following resources for JavaScript:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/">freeCodeCamp</a> for a free, in-depth, JS curriculum</li>
</ul>
<ul>
<li><p><a target="_blank" href="https://www.w3schools.com/js/default.asp">w3schools.com</a> for basic JavaScript tutorial</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/js-interview-prep-handbook/">JavaScript Interview Prep Handbook</a> for important JavaScript concepts.</p>
</li>
</ul>
<p>There are a lot of other resources for JavaScript, but I won’t overwhelm you with too many. These two should be enough to get started.</p>
<p>Once you are familiar with HTML, CSS, and JavaScript, you’ll know how to create a simple web page. Keep practicing by building different web pages, such as to-do lists and forms, and try implementing CRUD (Create, Read, Update, Delete) features.</p>
<h3 id="heading-learn-frontend-frameworks-and-libraries">Learn Frontend Frameworks and Libraries</h3>
<p>As your website grows, the JavaScript code becomes more and more complex and harder to maintain. This slows down the development process and makes it really challenging for developers.</p>
<p>To address these issues, you can use frameworks and libraries. Frameworks provide a more structured way to build web apps, encouraging modular design and reusability.</p>
<p>By using frameworks, you can focus on building actual features rather than handling the complexities of JavaScript code, which helps you speed up the development process. So I suggest picking up one JS framework/library to develop bigger projects.</p>
<h4 id="heading-reactjs-a-good-option">React.js – a good option</h4>
<p>React JS is a JavaScript library that makes it easy to create dynamic and interactive web pages. It divides your code into components, making it easy to read and maintain. This reduces code complexity and allows reusability.</p>
<p>React is my personal suggestion since it has a gentler learning curve compared to other frameworks. It is in very high demand among frontend roles, as many web apps are built in React.</p>
<p>To start learning React, your best resource is the <a target="_blank" href="https://react.dev/learn">React Docs</a>. They are very detailed, and include interactive code editors to play around with.</p>
<p>The freeCodeCamp YouTube channel also has some helpful React courses, like <a target="_blank" href="https://www.freecodecamp.org/news/learn-react-2024/">this one from Bob Ziroll</a>, and the Frontend Development Libraries certification has a <a target="_blank" href="https://www.freecodecamp.org/learn/front-end-development-libraries/#react">React section as well</a>.</p>
<p>Apart from React, there are other JavaScript frameworks like Angular, Vue, and the jQuery library. These remain popular as well, and depending on which tools are in demand in your area, you can focus on the one that will meet your needs the best.</p>
<p><strong>Note:</strong> Make sure you learn all the basic JavaScript concepts and understand them fully before jumping into any framework.</p>
<h3 id="heading-learn-responsive-design">Learn Responsive Design</h3>
<p>Before moving on, let’s talk about a fundamental practice in web development.</p>
<p>Responsive design refers to an approach where your design adjusts to fit screens of all sizes, ranging from desktops to tablets and mobiles. A good responsive design drastically reduces the need to write separate code for different screen sizes.</p>
<p>Here’s an interesting fact: <em>mobile phones make up two-thirds of web usage in the entire world.</em> So, to ensure a good user experience, you need to make the website look good on mobile phones.</p>
<p>Learn more about responsive design in this <a target="_blank" href="https://levelup.gitconnected.com/read-this-to-make-your-website-responsive-35af4ab7992b">simple guide</a>, and read more about <a target="_blank" href="https://www.freecodecamp.org/news/responsive-design-best-practices/">some best practices here</a>.</p>
<p>And here are some other resources that can help you on your frontend journey:</p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn">MDN Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/@WebDevSimplified">WebDevSimplified</a> - YouTube Channel</p>
</li>
</ul>
<h2 id="heading-backend-development">Backend Development</h2>
<p>Backend Development involves building the server-side of web applications. The server-side hosts the business logic of a website, that powers everything behind the scenes. It is also responsible for managing databases and ensuring smooth flow of data between server and the UI.</p>
<p>To dive into backend development, you need to learn a programming language first.</p>
<h3 id="heading-why-should-you-learn-a-programming-language">Why should you learn a programming language?</h3>
<p>Learning a programming language equips you with the foundations to build these server-side applications. Think of a language as a way to tell the server what you want it to do.</p>
<p>A programming language serves as a tool to solve problems and create robust, working applications. These languages have various capabilities for handling tasks like storing and managing data, communicating with the front end, and ensuring application security.</p>
<p>Learning a programming language isn’t just about learning the syntax and writing code. It’s about understanding how to create systems that drive a successful website. So, getting familiar with a programming language is a key part of backend development.</p>
<p>There are a number of programming languages out there, each with its own features. Let’s understand a few options:</p>
<h3 id="heading-python">Python</h3>
<p>Python is one of the preferred choices for backend development because of its simplicity. It has a concise and readable syntax making it very popular. It offers good features for database connections and setting up web servers. Python also has libraries for data science and machine learning.</p>
<p>Python is has a lot of tutorials and good community support, making it easy to get started with. It is beginner friendly, fun to learn and has a high demand.</p>
<p>Refer to the following resources for learning Python:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/ultimate-beginners-python-course/">Ultimate Python Beginner’s Course</a> on freeCodeCamp’s YouTube channel</p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/python-programming-language-tutorial/">GeeksforGeeks</a> Python Tutorial</p>
</li>
<li><p><a target="_blank" href="https://youtu.be/vLqTf2b6GZw?si=hcggX88jmrVYvpC5">Python Tutorial for Beginners on YouTube</a> (Hindi)</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/learn/machine-learning-with-python/">Machine Learning with Python</a> – freeCodeCamp certification</p>
</li>
</ul>
<h3 id="heading-golang">Golang</h3>
<p>Golang (Go) is increasing in popularity because of its simplicity and efficiency. Go code executes quickly and efficiently, making it a good option for high performance needs. This also leads to faster development time. Go also has excellent support for <a target="_blank" href="https://gowthamy.medium.com/concurrent-programming-introduction-1b6eac31aa66">concurrency</a>, which leads to efficient processing.</p>
<p>Go is beginner-friendly and has a clean and concise syntax, making it easy to read and maintain. It also has an extensive standard library offering a many built-in functions and tools, so it’s easy to set up a project without much hassle.</p>
<p>Go is growing in popularity because of its efficiency, and many companies are adopting Go for their projects. This has lead to an increasing demand for Golang developers and it’s expected to go up.</p>
<p>Go offers plenty of resources and a growing community for beginners. To get started with Go, refer to the following resources:</p>
<ul>
<li><p><a target="_blank" href="https://go.dev/tour/welcome/1">Tour of Go</a> – Interactive Learning with basic Golang concepts</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/go-beginners-handbook/">Golang Handbook</a> from Flavio Copes</p>
</li>
<li><p><a target="_blank" href="https://go.dev/doc/">Go Docs</a> – Very detailed</p>
</li>
</ul>
<h3 id="heading-java">Java</h3>
<p>Java is an <a target="_blank" href="https://medium.com/gitconnected/come-and-join-the-beautiful-world-of-java-9cedc815bafa">Object-Oriented Programming</a> (OOP) language, widely used for backend development. Java is known for its security and robustness, making it a preferred choice for applications that require high reliability such as financial and healthcare systems. Java also offers a great support for concurrency.</p>
<p>Java is a good option for beginners as it has extensive resources and a large developer community. This includes plenty of tutorials and detailed documentation to make life easier for beginners as well as experienced developers.</p>
<p>Java has been around for a while, and many existing systems and enterprise applications currently run on Java. So, there is a huge demand for Java developers among big enterprises.</p>
<p>Lastly, the concepts that you learn while coding in Java stick with you and make you a better developer, even if you switch languages going forward.</p>
<p>The following resources can help you get started with Java:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=A74TOX803D0">Java Programming for Beginners on freeCodeCamp.org</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-programming-concepts-java/">Objects-Oriented Programming in Java</a></p>
</li>
</ul>
<h3 id="heading-javascript-1">JavaScript</h3>
<p>We already know what JavaScript offers to frontend, but it can also be used for backend development through NodeJS.</p>
<p>NodeJS is a run time environment that allows you to run JS code on the server side. This makes it possible to use JavaScript for both the frontend and the backend.</p>
<p>NodeJS follows an event-driven architecture and asynchronous programming, which enables it to handle multiple tasks without stopping execution for a single one (non-blocking I/O). Node is single threaded, so instead of creating multiple threads to handle tasks, it executes them one by one asynchronously by queuing tasks.</p>
<p>Node also follows a modular architecture, meaning you can break your application into smaller, manageable components. It also includes <a target="_blank" href="https://docs.npmjs.com/about-npm">NPM</a> (Node Package Manager) which provides access to thousands of open-source libraries to add functionality like routing, authentication, or database handling.</p>
<p>Why use Node?</p>
<ul>
<li><p>This is a very good option if you are already familiar with JavaScript, as you don’t need to learn any other language.</p>
</li>
<li><p>Node is fast and efficient, making it easy if you want to set up a small server quickly.</p>
</li>
<li><p>Node also has a large ecosystem of libraries through NPM.</p>
</li>
</ul>
<p>However, Node is not ideal for CPU-intensive tasks as they can block the main thread, since it’s single threaded.</p>
<h3 id="heading-how-to-choose-a-programming-language">How to choose a programming language?</h3>
<p>With so many options available, it may feel confusing to choose the right one for you. Each language has its own capabilities and no language is objectively better than the other.</p>
<p>Python and Golang are very beginner-friendly with simple syntax. So, if you value a gentle learning curve, then these two are good options. Java is known for its reliability and robustness, with a lot of enterprise-level applications built using Java.</p>
<p>As for the job opportunities, there’s <a target="_blank" href="https://codeop.tech/blog/programming-languages-in-demand/">high demand</a> for each of the above languages, so you can choose any one you want. The most important thing is to develop your problem solving skill and understand how reliable software is built.</p>
<p>The choice of language doesn’t really matter in the long run, since the core fundamentals remain the same. So, my advice is to pick any language, learn its syntax and core capabilities, and start solving problems. You can start with the following:</p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/how-to-start-learning-dsa/">Learn Data Structures and Algorithms</a></p>
</li>
<li><p><a target="_blank" href="https://leetcode.com/discuss/study-guide/623011/A-guide-for-dummies-\(like-me\)">Start solving problems on LeetCode</a></p>
</li>
<li><p>Learn language specific frameworks and develop projects (Upcoming section)</p>
</li>
</ul>
<h3 id="heading-backend-development-frameworks">Backend Development Frameworks</h3>
<p>Programming languages alone are not enough to create robust and secure applications. Frameworks, built on the capabilities of these languages, allow you to create these powerful applications. By providing additional functionalities like routing and database handling, they serve as a platform to put your coding skills to the test and also make the development process faster.</p>
<p>Depending on your language of choice, you can learn the following frameworks:</p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction">Django</a> and <a target="_blank" href="https://www.geeksforgeeks.org/python-introduction-to-web-development-using-flask/">Flask</a> – Python Based Frameworks</p>
</li>
<li><p><a target="_blank" href="https://spring.io/projects/spring-boot">Java Spring Boot</a></p>
</li>
<li><p><a target="_blank" href="https://gin-gonic.com/docs/introduction/">Gin</a> – Golang framework (You can create a simple Golang application without using a framework)</p>
</li>
</ul>
<p>Read more about them if you are interested.</p>
<h3 id="heading-databases">Databases</h3>
<p>A database is a structured collection of data and is a crucial part of backend development. It plays an important role in storing and managing the application’s data.</p>
<p>Databases are broadly categorised into two types:</p>
<ul>
<li><p><strong>Relational Databases</strong> use tables to store data and define relationships between those tables. Examples are <a target="_blank" href="https://www.geeksforgeeks.org/what-is-mysql/">MySQL</a>, <a target="_blank" href="https://www.postgresql.org/about/">PostgreSQL</a>, <a target="_blank" href="https://www.simplilearn.com/tutorials/sql-tutorial/what-is-sqlite">SQLite</a>.</p>
</li>
<li><p><strong>Non-Relational Databases (NoSQL)</strong> are designed to handle unstructured or semi-structured data and are often used for hierarchical or document-based data storage. Examples are <a target="_blank" href="https://www.geeksforgeeks.org/what-is-mongodb-working-and-features/">MongoDB</a> and <a target="_blank" href="https://www.geeksforgeeks.org/apache-cassandra-nosql-database/">Cassandra</a>.</p>
<ul>
<li><p><strong>MongoDB</strong>: A popular NoSQL database for flexible and scalable data storage.</p>
</li>
<li><p><strong>Cassandra</strong>: Suitable for handling large amounts of distributed data.</p>
</li>
</ul>
</li>
</ul>
<p>To begin with relational databases, <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">learn SQL (Structured Query Language)</a>. SQL is used to write queries that perform various operations on the data, such as:</p>
<ul>
<li><p><strong>Creating</strong> tables and defining their structure.</p>
</li>
<li><p><strong>Reading</strong> data using SELECT statements.</p>
</li>
<li><p><strong>Updating</strong> existing records.</p>
</li>
<li><p><strong>Deleting</strong> unnecessary or outdated data.</p>
</li>
</ul>
<p>Refer to the following resources to learn SQL:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/a-beginners-guide-to-sql/">Full handbook on SQL</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3schools.com/sql/">w3schools.com</a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/sql-tutorial/">GeeksforGeeks</a> – Great resource to learn about database concepts</p>
</li>
</ul>
<p>Once you are familiar with basic SQL syntax and are able to write queries, explore <a target="_blank" href="https://www.geeksforgeeks.org/dbms/">DBMS (DataBase Management System)</a> concepts. These help you understand how databases are designed, managed, and optimised.</p>
<p>As a beginner, I recommend starting with relational databases because they provide a solid foundation in DBMS concepts involving tables and relationships between them. They are much more widely used among enterprises and learning their concepts can benefit you a lot.</p>
<p>These concepts might take some time to study, but don't worry about it. Take your time and keep working on the development stuff in parallel. You'll understand these concepts better as you gain more experience working with databases.</p>
<h3 id="heading-apis">APIs</h3>
<p>APIs (Application Programming Interfaces) are an essential part of backend development as they expose the backend logic to the outside world. APIs are a way for two different applications to communicate with each other. In the context of web development, the frontend interacts with the backend services through APIs.</p>
<p>When you build a web application, the frontend often needs to send and receive data from the backend. Let’s take an example of login functionality. When a user logs in, the frontend sends their credentials to the backend through an API call. The backend verifies this information and responds with the result.</p>
<p>To see these API calls, visit any website and open the Network Tab in Developer Tools. Interact with the website, or just reload the page, you’ll see the API calls being made as you use the website.</p>
<p>Read the following articles to understand more about APIs:</p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/what-is-an-api/">GeeksforGeeks - What is an API?</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/apis-for-beginners/">Full beginner-friendly course on APIs</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-apis-work/">How does an API work?</a></p>
</li>
</ul>
<p>At this point, you know how to start with both frontend and backend development. If you've reached this stage, congratulations! You've completed most of the hard work. But there’s one more thing you need to learn before you start developing projects.</p>
<h2 id="heading-git-and-github">Git and GitHub</h2>
<p>Git is a version control system that keeps track of changes in a software project. It allows multiple people to work on the project without directly interfering with each other’s work.</p>
<p>GitHub is a remote repository system based on Git. It is like social media, but for your code. GitHub encourages collaboration among developers and keeps track of everyone’s contributions.</p>
<p>GitHub lets you share your project code and view other developers' code, too. This facilitates increased collaboration and learning. I strongly recommend learning Git, especially at the beginning of your development journey.</p>
<p>To get started with Git and GitHub, refer to the following articles:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-git-in-under-10-minutes-da548267cc91/">Learn the Basics of Git in Under 10 Minutes</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/gitting-things-done-book/">Full book on Git and GitHub + version control basics</a></p>
</li>
<li><p><a target="_blank" href="https://docs.github.com/en/get-started/start-your-journey">Getting Started with GitHub</a></p>
</li>
</ul>
<h2 id="heading-build-a-portfolio-of-projects">Build a Portfolio of Projects</h2>
<p>Now, you are ready to start working on projects. A strong portfolio of projects is essential for showcasing your skills. It also helps you apply what you have learned so far and improves your problem-solving skills.</p>
<p>Consider the following project ideas:</p>
<ul>
<li><p>Todo App</p>
</li>
<li><p>E-Commerce App</p>
</li>
<li><p>Personal Portfolio website</p>
</li>
<li><p>Weather App – Use a public API and create a simple UI</p>
</li>
<li><p>Expense Tracker</p>
</li>
</ul>
<p>You can research more about these ideas and start with some basic features that come to mind. Build either the frontend, the backend, or both, depending on your goals. Share your projects on GitHub to increase their visibility.</p>
<p>Check out <a target="_blank" href="https://www.geeksforgeeks.org/web-development-projects/">GeeksforGeeks</a> for more project ideas.</p>
<h2 id="heading-deployment-and-hosting-platforms">Deployment and Hosting Platforms</h2>
<p>Once you have developed a web project, you can choose to release it to the public. This means that your website will be available on the internet for the public to use. How exciting is that!</p>
<p>Let’s understand the above terms. <strong>Deployment</strong> refers to the process of uploading your application to a remote system or a server in order to make it live and available to users. <strong>Hosting</strong> is like renting a space on the Internet for storing your application code. It provides a space to keep your website’s data on the server and displays your website on the internet.</p>
<p>Deploying and Hosting an application mainly follows these steps:</p>
<ul>
<li><p>The application code is written, tested locally, and optimised for production</p>
</li>
<li><p>The required configurations and secrets (passwords, API keys, and so on) are written as environment variables</p>
</li>
<li><p>The code is pushed to a version control system like GitHub or GitLab</p>
</li>
<li><p>The code is scanned for any security vulnerabilities and automated tests are run</p>
</li>
<li><p>Hosting platforms pull the code from these repositories and make it accessible on the internet.</p>
</li>
</ul>
<p>Hosting services like <a target="_blank" href="https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/">Netlify</a>, <a target="_blank" href="https://pages.github.com/">GitHub Pages</a>, and <a target="_blank" href="https://www.heroku.com/">Heroku</a> offer free and paid services and are easy to use for beginners. Netlify only supports frontend applications while Heroku is good for backend and full stack applications with easy integration of databases. GitHub Pages lets you host right from your repository.</p>
<p>Releasing your website to the public is a great opportunity to showcase your work to recruiters and potential collaborators.</p>
<h2 id="heading-additional-tips">Additional Tips</h2>
<ol>
<li><p>Don't spend too much time on tutorials, as you might get stuck in "tutorial hell." Tutorials are important for understanding core concepts, but real learning happens when you work hands-on. So start building as soon as you can, even if it’s just small projects at first.</p>
</li>
<li><p>JavaScript might seem overwhelming at first, but start small and practice regularly. Don’t rush to learn multiple things at once, tackle one concept at a time and practice through code for better understanding.</p>
</li>
<li><p>Experiment with different frameworks initially to find one that works for you. Once you choose a framework, stick with it until you learn it well.</p>
</li>
<li><p>Ensure that your programming language concepts are clear before jumping into any framework.</p>
</li>
<li><p>If you feel that a programming language is not working for you, you can switch to a different one, the core fundamentals remain the same.</p>
</li>
<li><p>As a beginner, it's important to have a basic understanding of both the frontend and the backend. Later, you can choose to specialise in one or you can choose to focus on both, becoming a "full stack" developer.</p>
</li>
<li><p>You will face challenges at first, so don't get discouraged. Keep practicing, and you will get better over time.</p>
</li>
<li><p>If you are stuck on any issue, use Chat GPT, Google Search, forums and developer communities, and Stack Overflow as much as possible. I am always available if you need any help.</p>
</li>
<li><p>Lastly, stay updated with the latest trends and technologies in web development. Always look for new or improved ways to solve problems. Learning never stops!</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Web Development is divided into two parts: frontend and backend development. The frontend is concerned with the website’s appearance while the backend focuses on the server-side logic and databases.</p>
<p>HTML, CSS, and JavaScript are the essentials in frontend development and form the backbone of a website. In backend development, learning a programming language like Python or Java is key. Both frontend and backend frameworks provide additional capabilities and make the development process faster.</p>
<p>Git is a must-have skill as it allows you to share your work and collaborate with other developers. Building a portfolio of projects and sharing on GitHub showcases your work and makes you a better developer. Lastly, utilise deployment platforms as they make your website available to the general public.</p>
<p>That’s it for today! I hope this article helps you start your web development journey. Let me know what you think. Your feedback is always appreciated!</p>
<p>Connect with me on Twitter for more updates and discussions. If you have any questions or clarifications, feel free to reach out. Thank you for reading, and I look forward to seeing you next time!</p>
<h3 id="heading-references"><strong>References:</strong></h3>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/can-start-learn-web-development/">How to become a web developer</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started/Your_first_website">Building your first website</a></p>
</li>
<li><p><a target="_blank" href="https://medium.com/shecodeafrica/getting-started-with-backend-engineering-a-beginners-guide-2426759238ea">Getting started with backend engineering</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=CWAi_2oLhYg">Developer roadmap</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The React Interview Prep Handbook – Essential Topics and Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In the ever-changing landscape of web development, React is in very high demand. Companies are often seeking skilled React developers to build dynamic and engaging web applications. If you are a web developer or aspiring to be one, it's ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-interview-prep-handbook/</link>
                <guid isPermaLink="false">670902eb7e9f1a89f2aa0ed0</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Fri, 11 Oct 2024 10:50:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728643567956/00c98d19-4694-4942-9ad2-d2f25bcf05c0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In the ever-changing landscape of web development, React is in very high demand. Companies are often seeking skilled React developers to build dynamic and engaging web applications.</p>
<p>If you are a web developer or aspiring to be one, it's important to understand what these companies look for in candidates. Preparing for interviews at these companies can be a daunting task.</p>
<p>So, in this article, I am going to list some of the topics to help you prepare for your next React interview. We'll discuss each topic in detail, with examples, so you can get a good look before the interviews and possibly gain an edge over other candidates. Let's dive into it!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-javascript-fundamentals">JavaScript Fundamentals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-essentials">React Essentials</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-hooks">React Hooks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-concepts">Additional Concepts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-redux">React Redux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-notes">Additional Notes</a></p>
</li>
</ul>
<h2 id="heading-javascript-fundamentals">JavaScript Fundamentals</h2>
<p>To prepare for any web development interview, you need to get familiar with JavaScript fundamentals no matter what framework is listed in the job description. Framework based questions are always secondary to JavaScript fundamentals, so expect to get tested on JavaScript first.</p>
<p>If you are a beginner, you need to clear JavaScript fundamentals before jumping into React. A lot of people (including me) make the mistake of jumping straight into React after learning a bit of JavaScript.</p>
<p>I have written a detailed post on <a target="_blank" href="https://www.freecodecamp.org/news/js-interview-prep-handbook/">important JavaScript concepts for interviews</a>. You can include this as part of your React interview preparation. If you are clear on all JavaScript fundamentals, you can skip to the next section.</p>
<h2 id="heading-react-essentials">React Essentials</h2>
<p>Let's go through some essential topics you need to get familiar with:</p>
<h3 id="heading-what-is-virtual-dom-in-react">What is Virtual DOM in React?</h3>
<p>As we all know, the browser DOM (Document Object Model) is a tree-like structure of different HTML elements. Virtual DOM is an in-memory representation or a lightweight version of the real DOM. It is an abstraction created by React which is similar to the real DOM.</p>
<p>Why does React use the virtual DOM? Updating and re-rendering the real DOM is slow and inefficient, especially if it gets updated frequently. So, instead of updating the real DOM directly, React updates the virtual DOM.</p>
<p>The virtual DOM is then compared to the real DOM and once it identifies the differences, it only updates that part of the DOM, rather than rendering the entire DOM again. This process is known as <a target="_blank" href="https://legacy.reactjs.org/docs/reconciliation.html">diffing and reconciliation</a>.</p>
<h3 id="heading-what-is-jsx">What is JSX?</h3>
<p>JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in the same file as the JavaScript code. This makes it very easy for your HTML to work with JavaScript.</p>
<p>You can write JSX code in a <code>.js</code> or <code>.jsx</code> file. Consider the following <strong>MyComponent.jsx</strong> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> name = <span class="hljs-string">"Kunal"</span>
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            {name}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<h3 id="heading-what-is-state">What is State?</h3>
<p>State is a React object that contains information about the component and determines how the component behaves. State can change any time based on user behavior. Any change in state causes the entire component to re-render.</p>
<p>State is used to render dynamic information in the component and makes the UI interactive. State determines how a component reacts to events like user input and data manipulation, and controls what it renders on screen.</p>
<p>Some things you need to keep in mind while using state:</p>
<ul>
<li><p>States are immutable. Always update the state using a <code>setState</code> function. For objects/arrays, create new ones and set the state with the new array/object. This ensures proper component behavior.</p>
</li>
<li><p>Use state only when necessary, avoid storing redundant information as it may cause unnecessary re-renders.</p>
</li>
<li><p>Use the state locally in the same component, avoid passing state down the DOM tree, unless absolutely necessary. For global state, use context or redux.</p>
</li>
</ul>
<p>Check the <a target="_blank" href="https://legacy.reactjs.org/docs/state-and-lifecycle.html">legacy docs</a> for state in class components. For functional components, refer to the <a class="post-section-overview" href="#heading-usestate-hook"><code>useState</code></a> section.</p>
<h3 id="heading-what-are-props">What are props?</h3>
<p>Props (short for properties) are a way to pass data from one component to another. They can be considered as arguments passed to components. Props are passed to a child component similar to HTML attributes.</p>
<p>Let's take an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> name = <span class="hljs-string">"John Doe"</span>;
  <span class="hljs-keyword">const</span> age = <span class="hljs-number">30</span>;

  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>)
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">age</span>=<span class="hljs-string">{age}</span> <span class="hljs-attr">handleClick</span>=<span class="hljs-string">{handleClick}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">{ name, age, handleClick }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name: {name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Age: {age}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>Here, the parent component passes down name, age and handleClick method as props to the child component.</p>
</li>
<li><p>These props form a <code>props</code> object that contains the values passed. Every functional component takes a <code>props</code> object as an argument</p>
</li>
<li><p>We have accessed the props by destructuring the object in the child component.</p>
</li>
</ul>
<p>Props can only be passed one way down the component tree. That is, from parent to child component. Props are read-only, you cannot change their value directly. State values passed down as props can be updated using state update function.</p>
<h3 id="heading-difference-between-class-and-functional-components">Difference Between Class and Functional components</h3>
<p>React components are of two types: class and functional components. Let's understand the difference between the two:</p>
<p><strong>Class Components:</strong></p>
<ul>
<li><p>Class components are written using ES6 classes. Its properties and functions are accessed using the <code>this</code> keyword. They need a <code>render</code> method to return JSX.</p>
</li>
<li><p>Class components are stateful components that contain built-in features like State and Context.</p>
</li>
<li><p>They have methods for different stages of component lifecycle: <code>componentDidMount()</code> <code>componentDidUpdate()</code> <code>componentWillUnmount()</code>, and so on.</p>
</li>
<li><p>Class components are verbose, hard to read and always need <code>this</code> keyword to access properties.</p>
</li>
</ul>
<p><strong>Functional Components:</strong></p>
<ul>
<li><p>Functional components are simple JavaScript functions that take a <code>props</code> object as an argument. They don't need a <code>render</code> method, they return JSX directly.</p>
</li>
<li><p>Functional components are stateless and do not have state of their own. Instead, they use Hooks to use class component features like State or Context.</p>
</li>
<li><p>There are no lifecycle methods, lifecycle is be managed with <code>useEffect</code> hook.</p>
</li>
<li><p>Functional components require less code than class components, so they are easier to read and write.</p>
</li>
</ul>
<p>Nowadays, developers prefer and recommend functional components, especially with Hooks. Class components are usually found in older codebases.</p>
<p>However, knowing class components is helpful as a lot of companies have old codebases written using class components.</p>
<h3 id="heading-what-is-the-component-lifecycle">What is the Component Lifecycle?</h3>
<p>Every React component has a lifecycle that goes through three phases: Mounting, Updating and Unmounting.</p>
<p><strong>Mounting</strong></p>
<p>In this phase, a component is created and added to the DOM. When a component is mounted, the following methods are called:</p>
<ul>
<li><a target="_blank" href="https://www.geeksforgeeks.org/react-js-constructor-method/"><code>constructor()</code></a></li>
</ul>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/react-js-static-getderivedstatefromprops/"><code>static getDerivedStateFromProps(props, state)</code></a> (rarely used)</p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/react-js-render-method/"><code>render()</code></a></p>
</li>
<li><p><code>componentDidMount()</code></p>
</li>
</ul>
<p><code>componentDidMount()</code> is called only once; that is, when the component mounts. It is the preferred method for executing side effects when a component loads for the first time. In functional components, its equivalent is <code>useEffect</code> Hook.</p>
<p><strong>Updating</strong></p>
<p>In updating phase, the component's state or props change, which causes the component to re-render. The following methods are called when component updates:</p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/reactjs-shouldcomponentupdate-method/"><code>shouldComponentUpdate(nextProps, nextState)</code></a></p>
</li>
<li><p><code>render()</code> (called again)</p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/reactjs-getsnapshotbeforeupdate-method/"><code>getSnapshotBeforeUpdate()</code></a></p>
</li>
<li><p><code>componentDidUpdate()</code></p>
</li>
</ul>
<p>The <code>componentDidUpdate</code> method is called following times:</p>
<ul>
<li><p>The first time when component mounts, after the <code>componentDidMount</code> method.</p>
</li>
<li><p>Any state or props change triggering component re-render.</p>
</li>
</ul>
<p>It is useful to execute side effects when a state updates. In functional component, the equivalent is <code>useEffect</code> with dependencies.</p>
<p><strong>Unmounting</strong></p>
<p>In this phase, the component is removed from the DOM. The <code>componentWillUnmount</code> method is called while unmounting.</p>
<p>It is mostly used for cleanup tasks before the component unmounts. Refer to the <a class="post-section-overview" href="#heading-useeffect-hook"><code>useEffect</code></a> section for its equivalent.</p>
<h3 id="heading-controlled-and-uncontrolled-components">Controlled and Uncontrolled components</h3>
<p>In controlled components, the form elements are managed by React state. This means that the values of form fields are set and updated ("controlled" by React state). All form data is stored in state before submitting the form.</p>
<p>Example of controlled component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ControlledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">`Value: <span class="hljs-subst">${value}</span>`</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setValue(e.target.value)} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>The value of the <code>input</code> field is being controlled by React state variable <code>value</code>.</p>
</li>
<li><p>When you update the input field, the state gets updated and value of the input is set accordingly.</p>
</li>
</ul>
<p>Uncontrolled components, on the other hand, do not depend on state to manage forms. Instead, the values of form fields are managed internally, usually with refs. Refs are used to directly interact with the DOM elements and update values without updating state and causing re-renders.</p>
<p>Example of uncontrolled component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UncontrolledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">`Input Value: <span class="hljs-subst">${inputRef.current.value}</span>`</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, we have used a ref to directly access the input element's DOM node and used its value to access form data. This makes form handling much simpler compared to using state.</p>
<p>When to use either:</p>
<ul>
<li><p>Use controlled components if you want more control over data that the user inputs. This is particularly useful when two form fields are dependent on each other.</p>
</li>
<li><p>If you have multiple state dependent on the form data, using state is a good practice.</p>
</li>
<li><p>Use uncontrolled components if your form is very simple and there's no need to manipulate the form data.</p>
</li>
</ul>
<h3 id="heading-what-are-pure-components">What are Pure Components?</h3>
<p>A pure component is similar to a normal component, except that it only renders if its state or props have changed.</p>
<p>Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> PureExample = React.memo(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Hello {this.props.name} <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setName(e.target.value)} /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setToggle(!toggle)}&gt; Toggle <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PureExample</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p><code>PureExample</code> is a pure component that is a child of <code>App</code> component. Pure components can be created by surrounding the function with <code>React.memo()</code>.</p>
</li>
<li><p>In the example, we have an <code>input</code> field that updates <code>name</code>, and a button that toggles the state, <code>toggle</code>.</p>
</li>
<li><p><code>name</code> is passed down as props to <code>PureExample</code>, so it re-renders if <code>name</code> is updated. If you update <code>toggle</code> or any other state, <code>PureExample</code> does not re-render.</p>
</li>
</ul>
<p>In case of class components, pure components can be created by extending the <code>PureComponent</code> class. However, functional components are recommended.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PureExample</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">PureComponent</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Hello {this.props.name} <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
  }
}
</code></pre>
<p>Usually, when parent component re-renders, React renders all its child components again, even if none of the child components have updated.</p>
<p>Pure components are used for child components that only need to re-render if one of their props change. This skips unnecessary re-renders and improves performance.</p>
<h2 id="heading-react-hooks">React Hooks</h2>
<p>React Hooks is a game-changing feature introduced to React in 2016. Hooks provide a way to implement class component features in functional components. Because of hooks, developers nowadays prefer functional to class components.</p>
<h3 id="heading-usestate-hook">useState Hook</h3>
<p>We have already seen what state is. Let's understand how to implement state in functional components with a simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> increment = <span class="hljs-function">() =&gt;</span> {
    setCount(count + <span class="hljs-number">1</span>);
};
<span class="hljs-keyword">const</span> decrement = <span class="hljs-function">() =&gt;</span> {
    setCount(count - <span class="hljs-number">1</span>);
};
<span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{decrement}</span>&gt;</span>Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<ul>
<li><p><code>useState</code> function takes an initial value as an argument and returns an array containing two elements: the current state, and a state update function.</p>
</li>
<li><p>In this example, we have two buttons that increment and decrement the count. On click of the button, the increment/decrement operations are performed by updating the <code>count</code> state.</p>
</li>
<li><p>The component re-renders and displays the updated <code>count</code>.</p>
</li>
</ul>
<p>For more examples of its usages, check out my post below:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://levelup.gitconnected.com/4-different-examples-of-the-usestate-hook-in-react-5504ce011a20">https://levelup.gitconnected.com/4-different-examples-of-the-usestate-hook-in-react-5504ce011a20</a></div>
<p> </p>
<h3 id="heading-useeffect-hook">useEffect Hook</h3>
<p>The <code>useEffect</code> hook is used to implement side effects in a component. Side effects include API calls, subscription to a service and DOM manipulation. <code>useEffect</code> can also be used to conditionally update a state based on another state change.</p>
<p>Let's understand how to use it, with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState([]);
  <span class="hljs-keyword">const</span> [page, setPage] = useState(<span class="hljs-number">1</span>);
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://api.example.com/data?page=<span class="hljs-subst">${page}</span>`</span>);
      <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
      setData(result);
    };

    fetchData();
  }, [page]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> {JSON.stringify(data)} <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setPage(page - 1)} disabled={page <span class="hljs-tag">&lt;<span class="hljs-name">=</span> <span class="hljs-attr">1</span>}&gt;</span>
        Previous
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setPage(page + 1)}&gt;Next<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p><code>useEffect</code> takes two arguments: a function that performs side effects and a dependency array.</p>
</li>
<li><p>In this example, we display paginated data by including the fetching logic inside a <code>useEffect</code> and including the current page in the dependency.</p>
</li>
<li><p><code>useEffect</code> makes the API call on the first render, loading the first page of data. After that, it loads additional data every time user changes the page.</p>
</li>
</ul>
<p>How to implement lifecycle methods in <code>useEffect</code>:</p>
<ul>
<li><p>To implement <code>componentDidMount()</code>, pass an empty dependency array</p>
</li>
<li><p>To implement <code>componentDidUpdate()</code>, pass dependencies to run the <code>useEffect</code> if one of those dependencies changes</p>
</li>
<li><p>For <code>componentWillUnmount()</code>, return a callback function from <code>useEffect</code> containing the cleanup code</p>
</li>
</ul>
<p><code>useEffect</code> can be used in a lot of ways. The React <a target="_blank" href="https://react.dev/reference/react/useEffect#usage">docs</a> contain several examples of usages.</p>
<h3 id="heading-usecontext-hook">useContext Hook</h3>
<p>States are used to store information about a component and controls how the component behaves. In some cases, child components need access to the parent component’s state.</p>
<p>To achieve this we pass down the state data as props. However, passing data through props may lead to issues. Let’s understand the biggest issue:</p>
<p><strong>What is Prop Drilling?</strong></p>
<p>To pass data from parent to child component, we use props. But what if a component deep within the component tree needs access to a prop. You would need to pass it through several components that don't even need the prop.</p>
<p>The same issue arises when multiple components in different branches of the tree need access to the same prop.</p>
<p>Passing down props through numerous components leads to a situation known as prop drilling.</p>
<p><strong>How does React context solve the problem?</strong></p>
<p>Context lets parent components pass data to all components in the tree without drilling props through them. This eliminates the need to pass down props through multiple components in the tree.</p>
<p>Context was introduced as a <a target="_blank" href="https://legacy.reactjs.org/docs/context.html">class component feature</a> initially, but now it can be used in functional components with the <code>useContext</code> hook.</p>
<p>Let's see how to use the hook:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, {useContext} <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> DataContext = React.createContext(<span class="hljs-literal">null</span>);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DataContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Some value"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MainComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">DataContext.Provider</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MainComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> data = useContext(DataContext);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> Data: {data} <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<ul>
<li><p>We used <code>React.createContext</code> method to create a context and then created a provider function that wraps around the main component.</p>
</li>
<li><p>The <code>value</code> prop of <code>DataContext.Provider</code> is used the pass data to the entire component tree under <code>MainComponent</code>.</p>
</li>
<li><p>The <code>useContext</code> Hook consumes this data inside components. It returns the data that was passed to the <code>value</code> prop of the provider.</p>
</li>
</ul>
<p><code>useContext</code> can only be used if the component or one of its parents has a context provider wrapped around it. Examples use cases are themes, user info, language preferences and localization, and so on.</p>
<p>Check out additional usages of <code>useContext</code> in the <a target="_blank" href="https://react.dev/reference/react/useContext#usage">docs</a>.</p>
<h3 id="heading-useref-hook">useRef Hook</h3>
<p>Refs (short for references) are a way to interact directly with DOM elements. They give you direct access to the JavaScript DOM object and its <a target="_blank" href="https://www.tutorialspoint.com/javascript/javascript_dom_methods.htm">methods</a>.</p>
<p>Visit the <a target="_blank" href="https://legacy.reactjs.org/docs/refs-and-the-dom.html">legacy docs</a> for using refs in class components. In functional components, we have the <code>useRef</code> Hook. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> myRef = useRef(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    myRef.current.focus();
  }, []);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{myRef}</span> /&gt;</span></span>;
}
</code></pre>
<ul>
<li><p><code>useRef</code> takes an initial value as an argument and returns a <code>ref</code> object.</p>
</li>
<li><p>When this <code>ref</code> object is passed to the <code>ref</code> prop of an element, we get a direct reference to the element's DOM node.</p>
</li>
<li><p>The value of a <code>ref</code> is stored inside its <code>current</code> property.</p>
</li>
<li><p>Since <code>ref</code> is a JavaScript DOM object, we can call the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus">focus()</a> method to focus on the <code>input</code> element when the component mounts.</p>
</li>
</ul>
<p>Unlike state, refs do not cause component re-renders and unlike local variables, refs retain their values between renders.</p>
<p>Some things to remember about refs:</p>
<ul>
<li><p>Components can expose their DOM nodes to parent components by using <a target="_blank" href="https://react.dev/reference/react/forwardRef">forwardRef</a>.</p>
</li>
<li><p>Only use refs when you absolutely need to access DOM elements. Example use cases could be for tasks like focusing on input elements, selecting tests, triggering animations, determining elements positions, and so on.</p>
</li>
<li><p>Avoid over-using them, prefer state and props over refs. Avoid modifying DOM elements explicitly to control component behavior, use state instead.</p>
</li>
</ul>
<h3 id="heading-usememo-hook">useMemo Hook</h3>
<p>If your component needs to perform an intensive calculation while rendering something, it slows down website performance since the component executes the calculation on every render.</p>
<p>This may be acceptable for a state value dependent on it, but it's inefficient if the expensive function executes again on other, unrelated state updates. To tackle this, we memoize the result of the calculation and re-calculate it only when the relevant state changes.</p>
<p><code>useMemo</code> Hook is used to memoize the result of this calculation, so that it doesn't run on every render. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MemoExample = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [computedValue, setComputedValue] = useState(value);
  <span class="hljs-keyword">const</span> [otherState, setOtherState] = useState(<span class="hljs-string">'Initial State'</span>);

  <span class="hljs-keyword">const</span> expensiveFunction = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000000</span>; i++) {
          result += i * <span class="hljs-number">2</span>;
      }
      <span class="hljs-keyword">return</span> result;
  }

  <span class="hljs-keyword">const</span> value = useMemo(expensiveFunction, [computedValue]);

  <span class="hljs-keyword">return</span>  (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setComputedValue(computedValue + 1)}&gt;
            Re-calculate
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setOtherState('State Changed')}&gt;
        Change Other State
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<ul>
<li><p><code>useMemo</code> takes in the function and a dependency array as arguments, and returns the result of this function. It memoizes the result for the next render and returns the memoized value unless some dependency changes.</p>
</li>
<li><p>We have passed <code>computedValue</code> state inside the array, so, after running on the first render, the function will run only when <code>computedValue</code> changes.</p>
</li>
<li><p>If you update any other state, the component re-renders, but the function does not run again.</p>
</li>
</ul>
<p>When to use:</p>
<ul>
<li><p>If you do not want to run a function on every render, except for the state dependent on it.</p>
</li>
<li><p>To maintain referential equality of arrays and object across renders. Array/object references change each time they are declared.</p>
</li>
<li><p>When rendering lists with <a target="_blank" href="http://Array.map"><code>Array.map</code></a> that do not need to change except for relevant state updates.</p>
</li>
</ul>
<h3 id="heading-usecallback-hook">useCallback Hook</h3>
<p><code>useCallback</code> is similar to <code>useMemo</code>, the only difference is that <code>useCallback</code> caches the function definition itself, rather than memoizing its return value.</p>
<p>Similar to arrays or objects, a function reference changes each time it is declared. So, wrapping it around a <code>useCallback</code> maintains referential equality of the function across renders.</p>
<p>Let's understand it with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> handleSubmit = useCallback(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Child component form submitted'</span>);
  }, []); <span class="hljs-comment">// Add props or state that this function depends on</span>
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{toggle</span> ? '<span class="hljs-attr">dark</span>' <span class="hljs-attr">:</span> ''}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setToggle(!toggle)}&gt; Toggle Theme <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Child</span> <span class="hljs-attr">handleSubmit</span>=<span class="hljs-string">{handleSubmit}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">const</span> Child = React.memo(<span class="hljs-function">(<span class="hljs-params">{ handleSubmit }</span>) =&gt;</span> {

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    <span class="hljs-comment">// Assume component is slow</span>
  }
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span> Child component <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span> Click Me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
});
</code></pre>
<ul>
<li><p>Here, we deliberately slow down the child component to simulate slow renders. Since it's wrapped inside <code>React.memo()</code>, it only re-renders if its only prop <code>handleSubmit</code> changes.</p>
</li>
<li><p>But when <code>toggle</code> state changes, it triggers a re-render for the child component as well, even if it's not passed down to the child component.</p>
</li>
<li><p>This is because, every time the parent component renders, the <code>handleSubmit</code> function is created with a new reference. So, technically <code>handleSubmit</code> has changed and thus, the child component re-renders.</p>
</li>
<li><p>To avoid this behaviour, we wrap the <code>handleSubmit</code> function declaration inside a <code>useCallback</code>. This ensures that the function reference remains the same between renders.</p>
</li>
<li><p>In our example, the function is created only once, since there are no dependencies. If you add dependencies, the function is re-created only if one of them changes.</p>
</li>
</ul>
<p>When to use:</p>
<ul>
<li><p>When you have event handlers defined for an element inside your component, wrap them inside a <code>useCallback</code> to avoid unnecessary re-creations of event handlers.</p>
</li>
<li><p>When you call a function inside a <code>useEffect</code>, you would usually pass the function as a dependency. To avoid running <code>useEffect</code> unnecessarily on every render, wrap the function definition inside a <code>useCallback</code>.</p>
</li>
<li><p>If your custom Hook is returning a function, it is recommended to wrap it inside a <code>useCallback</code>. So, the users don't have to optimize the Hook – rather, they can focus on their own code.</p>
</li>
</ul>
<p>If you want to learn more about <code>useMemo</code> and <code>useCallback</code> hooks, check out my post below:</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/">https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/">https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</a></div>
<p> </p>
<h3 id="heading-usereducer-hook">useReducer Hook</h3>
<p>The <code>useReducer</code> Hook is another way to manage state in React applications. As your application grows, its state gets more and more complex. With time, it becomes difficult to handle complex state logic with <code>useState</code> Hook.</p>
<p>useReducer offers a more structured way to manage complex state by handling all state updates in a reducer function. This makes state management easier since all the state update logic is at one place.</p>
<p>Let's see how to use this hook with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> reducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'INCREMENT'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'DECREMENT'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'RESET'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Unknown action type: <span class="hljs-subst">${action.type}</span>`</span>);
  }
};

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App'</span>&gt;</span>
      State: {state.count}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'INCREMENT' })}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'DECREMENT' })}&gt;Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'RESET' })}&gt;Reset<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>This example contains a simple counter state with three actions: increment, decrement and reset.</p>
</li>
<li><p>We define a reducer function that accepts the current state and an action object as arguments. The action object contains the action type (a string) and payload (data passed to the action).</p>
</li>
<li><p>The <code>useReducer</code> Hook accepts the reducer function and an initial state, and returns an array containing the current state and a <code>dispatch</code> method.</p>
</li>
<li><p>To update state, we call the <code>dispatch</code> method and pass the action type and payload in an object. We call this process, "dispatching an action".</p>
</li>
</ul>
<p>When to use <code>useReducer</code>:</p>
<ul>
<li><p>Use this hook only when your component has complex state update logic. Since it involves writing more code, prefer <code>useState</code> for simpler state updates. The simple example provided is just for demonstration purpose.</p>
</li>
<li><p>When there are a lot of state update actions with different logic, it makes sense to have them all in a separate function. With this, you just pass the action type and payload to a <code>dispatch</code> function and the reducer handles the state update.</p>
</li>
</ul>
<p>If you want to understand more about the <code>useReducer</code> hook, check out my post:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/usereducer-hook-react/">https://www.freecodecamp.org/news/usereducer-hook-react/</a></div>
<p> </p>
<p>So far, we have covered the most common hooks that React provides. Besides these, React also offers additional, less commonly uses hooks. So, if you are interested, read about them in the <a target="_blank" href="https://react.dev/reference/react/hooks">docs</a>. However, learning the above hooks should be enough for your interviews.</p>
<h3 id="heading-custom-hooks">Custom Hooks</h3>
<p>There are some situations where you may need to create your own hooks on top of the existing ones. Custom hooks provide re-usable functionality across multiple components and contribute to cleaner, maintainable code.</p>
<p>To create a custom Hook, first identify a piece of functionality that you want to re-use. Then, you can export it as a function with its name starting with the prefix 'use'.</p>
<p>Let's say you have multiple components that need to fetch data from APIs. You can export the fetching logic as a Hook to avoid duplicating code.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useFetch</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
        <span class="hljs-keyword">if</span> (!response.ok) {
          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
        }
        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
        setData(result);
      } <span class="hljs-keyword">catch</span> (error) {
        setError(error);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    };

    fetchData();
  }, [url]);

  <span class="hljs-keyword">return</span> { data, loading, error };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useFetch;
</code></pre>
<ul>
<li><p>In the <code>useFetch</code> custom hook, we fetched the data inside a <code>useEffect</code> Hook, just as would inside a component. We also handled loading and error states in the Hook.</p>
</li>
<li><p>Finally, we return the data, with the loading and error states, allowing the component to use them for handling the rendering logic.</p>
</li>
</ul>
<p>Let's use this in a component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> UserList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { data, loading, error } = useFetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {data.map(user =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span>{user.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
};
</code></pre>
<p>The <code>UsersList</code> component displays a list of users fetched from an API, and also renders “Loading” text and an error if any. To use the custom Hook, we called <code>useFetch</code> just like any other hook, and passed an API endpoint. We can further modify the <code>useFetch</code> custom hook to include request headers, request body, etc.</p>
<p>This way, custom Hooks help you abstract the logic from a component and make it re-usable throughout the application. There are several other use cases:</p>
<ul>
<li><p>Event listeners for events like window resizing, mouse movements or keyboard presses.</p>
</li>
<li><p>Form handling, including form validation and submission.</p>
</li>
<li><p>Themes, caches, transitions, and so on.</p>
</li>
</ul>
<p>Check out the <a target="_blank" href="https://react.dev/learn/reusing-logic-with-custom-hooks">docs</a> to learn more about custom hooks.</p>
<h2 id="heading-additional-concepts">Additional Concepts</h2>
<p>Here are some additional concepts that can be helpful:</p>
<h3 id="heading-why-not-use-index-as-keys-while-rendering-lists">Why not Use Index as Keys while Rendering Lists?</h3>
<p>When you render lists in React using the <a target="_blank" href="http://Array.map"><code>Array.map</code></a> method, you are asked to provide a unique <code>key</code> prop to each item being rendered. This key is used to distinguish elements from each other.</p>
<p>Indices are unique, so it's tempting to use them as keys for simplicity. However, indices of elements are not stable.</p>
<p>Elements often get added or deleted in an array. The order of elements could get changed too. In these cases, value of <code>key</code> prop changes and may lead to unpredictable behavior.</p>
<p>Let's consider the following list:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> items = [
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item A'</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item B'</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item C'</span>
  }
]
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    {items.map((item, index) =&gt; (
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
        {item.name}
      <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    ))}
  <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
);
</code></pre>
<p>Each rendered item in the list has its index as the key. If we delete <code>Item B</code> from the list, the references of the other elements get changed.</p>
<p>React uses keys to uniquely identify list elements, so that rendering them becomes easier. React often re-uses these elements for quick renders. However, if an element gets deleted, the keys of all subsequent elements are updated.</p>
<p>React may reuse the deleted key or render the entire list again which could lead to performance issues. Instead of indices, choose something unique, preferably username, email or an ID generated by database.</p>
<h3 id="heading-higher-order-components">Higher Order Components</h3>
<p>A higher order component (HOC) is a function that takes a component as an argument and returns a new component that wraps the original one. HOCs allow you to provide additional functionality to a component as well as re-use it across multiple components.</p>
<p>Rather than providing a short explanation here, I would recommend the following article that explains HOCs with various examples:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/higher-order-components-in-react/">https://www.freecodecamp.org/news/higher-order-components-in-react/</a></div>
<p> </p>
<h3 id="heading-lazy-loading">Lazy Loading</h3>
<p>Lazy loading is a web development pattern that delays the loading of resources like images, videos, or non-essential components. It helps web pages load faster by first loading the content necessary for interaction, and then loading the rest of the content.</p>
<p>One example of lazy loading is an E-commerce product catalog page. The page first loads the names and prices of products and clickable elements. Then, it loads the images and other UI elements.</p>
<p>In React, lazy loading can be implemented using <code>React.lazy()</code> and <code>Suspense</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> LazyComponent = React.lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LazyComponent'</span>));

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Showing lazy component below<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LazyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<ul>
<li><p>Once you have identified a component to lazy load, use the <code>React.lazy()</code> function to dynamically import the lazy component.</p>
</li>
<li><p>Wrap the lazy-loaded component inside <code>Suspense</code>. It renders a fallback (default) component till the lazy component loads.</p>
</li>
</ul>
<p>This way, you can load a React component on demand. This is also known as code splitting<strong>.</strong> The code is split and some part of the React code is loaded dynamically when needed.</p>
<p>Code splitting optimizes the performance of React applications that have large, complex components. By using <code>Suspense</code>, you can display a temporary UI to the user, so they don't have to stare at a blank screen while a component is loading.</p>
<p>Code splitting breaks your application into several chunks, with each chunk being loaded independently. So, this process is also known as chunking<strong>.</strong></p>
<h3 id="heading-difference-between-client-side-and-server-side-rendering">Difference Between Client-side and Server-side Rendering</h3>
<p>There are two ways to render webpages in React. Let's have a look:</p>
<p><strong>Server Side Rendering (SSR):</strong></p>
<ul>
<li><p>Web Page is generated and rendered on the server before sending to the client. Client receives complete web page from the server and displays it directly to the user.</p>
</li>
<li><p>Loading the prepared HTML helps with faster loading times, improving the user experience. This is especially beneficial for users with slower internet connections.</p>
</li>
<li><p>Since the web page is already prepared, it helps search engines better index your website, making it more SEO-friendly.</p>
</li>
<li><p>SSR can increase server load if the page is updated frequently. Pages with dynamic content can take longer to update because they need to re-render often.</p>
</li>
<li><p>SSR is used for marketing, blogging and news websites where initial load times and SEO are important.</p>
</li>
</ul>
<p><strong>Client Side Rendering (CSR):</strong></p>
<ul>
<li><p>A basic HTML file is sent to the client, and then it renders dynamic content using JavaScript.</p>
</li>
<li><p>Initial load times are slower because preparing and rendering the content mostly happens on the client side.</p>
</li>
<li><p>Since it initially renders basic HTML and adds JavaScript content later, search engines may not be able to index your content, making it less SEO-friendly.</p>
</li>
<li><p>For web pages with dynamic content, rendering times are faster since all the rendering happens on client side.</p>
</li>
<li><p>CSR is used for websites with dynamic content and frequent user interactions like social media platforms or dashboards.</p>
</li>
</ul>
<h2 id="heading-react-redux">React Redux</h2>
<p>Redux is a state-management library that helps manage complex application state. It is a powerful library for managing state in large React applications.</p>
<p>In the context of React, let’s look at the Hooks Redux provides:</p>
<h3 id="heading-useselector">useSelector</h3>
<p>A selector function accepts a Redux state object as an argument and returns a part of that state. The <code>useSelector</code> Hook is used to call the selector function. Let's take the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// example state for e-commerce app</span>
<span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">users</span>: { 
        ...
    },
    <span class="hljs-attr">products</span>: {
        ...
    },
    <span class="hljs-attr">cart</span>: {
        ...
    }
    <span class="hljs-attr">orders</span>: {
        <span class="hljs-attr">ordersList</span>: [
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">101</span>,
                <span class="hljs-attr">status</span>: <span class="hljs-string">"Shipped"</span>
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">102</span>,
                <span class="hljs-attr">status</span>: <span class="hljs-string">"Processing"</span>
            },

            ...
        ]
    }
}
</code></pre>
<p>Let's say you want to display list of orders on a page. We can't access this state directly from the component as it’s part of the redux store. So, we use selector functions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectAllOrders = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.orders.ordersList
</code></pre>
<p>To call this selector function, we use the <code>useSelector</code> Hook:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> OrdersList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> orders = useSelector(selectAllOrders);
  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// display orders</span>
  );
};
</code></pre>
<p>The main advantage of using selectors is that you get access to the Redux state object, allowing you to access any slice of the state.</p>
<h3 id="heading-usedispatch">useDispatch</h3>
<p>The <code>useDispatch</code> Hook returns a function that you can use to dispatch actions, such as updating state and calling APIs. This function takes an action object as an argument and performs the corresponding action. This function is known as a dispatch function.</p>
<p>Let's take an example. We’ll work with the same state and update one of the order’s status:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> dispatch = useDispatch();

  <span class="hljs-keyword">const</span> handleUpdateStatus = <span class="hljs-function">() =&gt;</span> {
    dispatch({<span class="hljs-attr">type</span>: <span class="hljs-string">'ORDER_UPDATE_STATUS'</span>, <span class="hljs-attr">payload</span>: {
      <span class="hljs-attr">id</span>: <span class="hljs-number">102</span>,
      <span class="hljs-attr">status</span>: <span class="hljs-string">"Shipped"</span>
    }});
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Update Order Status<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleUpdateStatus}</span>&gt;</span>Mark as Delivered<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the action <code>ORDER_UPDATE_STATUS</code> will be dispatched with the corresponding payload. This action will be mapped to a reducer that will perform the state update.</p>
<p>The advantage of using dispatch is that you can just specify the action type and pass the payload and the state update logic will be handled by the reducer, instead of the component itself.</p>
<h3 id="heading-others">Others</h3>
<p>I have just listed two Hooks that React provides to work with Redux. However, if you are not familiar with Redux, you should check out the <a target="_blank" href="https://redux.js.org/introduction/getting-started">docs</a> to get started.</p>
<p>Redux is much more than just these two Hooks. Make sure you are clear on the core concepts: store, slices, reducers, actions, selectors, dispatch. <a target="_blank" href="https://redux-saga.js.org/docs/introduction/GettingStarted">Redux Sagas</a> is another major concept you should learn. They are mainly used for async operations.</p>
<h2 id="heading-additional-notes">Additional Notes</h2>
<p>There are a few other areas that I haven't mentioned so far, but can be a good addition:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/react-router-cheatsheet/">React Router</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-write-unit-tests-in-react/">Unit Testing in React</a></p>
</li>
</ul>
<p>Additionally, you may be asked to implement a small feature using the concepts I explained in this article. This gives you the opportunity to demonstrate your understanding of React.</p>
<p>Also, it's helpful to have a few React projects on your resume. Check out the <a target="_blank" href="https://www.freecodecamp.org/news/master-react-by-building-25-projects/">Master React by Building 25 Projects</a>.</p>
<p>Keep in mind that React is not limited to just these topics, there are additional resources in the References section. However, this handbook should serve as a useful guide before interviews. Feel free to keep re-visiting it during your interview preparation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this handbook, we outlined several important topics to prepare for your next React interview. We started with a few basic concepts in React, then moved to Hooks. Then, we saw a few additional concepts that are good to know before discussing React Redux.</p>
<p>I have written clear and concise explanations for each topic, with examples. That should help you articulate these concepts to interviewers. At places where I couldn't explain, I have pointed to other helpful resources that explain better. This makes the article your go-to place any time during your interview prep.</p>
<p>During the interviews, just stay calm and confidently demonstrate your knowledge. Good communication puts a nice impression on the interview. Lastly, remember that each interview is a learning opportunity - whether you succeed or not. Stay positive and keep refining your skills. All the best in your interviews!</p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/react-interview-questions-and-answers/">React Interview Questions – Interview Prep with Answers and Examples</a></p>
</li>
<li><p><a target="_blank" href="https://www.interviewbit.com/react-interview-questions/">React Interview Questions</a> - InterviewBit</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-react-key-concepts/#how-much-javascript-do-you-need-to-know-before-learning-react">Learn React – A Guide to the Key Concepts by Ankur Tyagi</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What's the Difference Between the useMemo and useCallback Hooks? ]]>
                </title>
                <description>
                    <![CDATA[ React provides various hooks that make it easier to manage application state and other React features in functional components. Hooks provide class component features to functional components, and they don't need a lot of code compared to class compo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</link>
                <guid isPermaLink="false">66d8514dec0a9800d5b8e6ea</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 15 Jul 2024 19:14:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/photo-1619410283995-43d9134e7656.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React provides various hooks that make it easier to manage application state and other React features in functional components. Hooks provide class component features to functional components, and they don't need a lot of code compared to class components.</p>
<p>Hooks also make your life easier by providing some convenient features. Among these hooks, we have <code>useMemo</code> and <code>useCallback</code> that help improve your website's performance.</p>
<p>In today's tutorial, we are going to discuss both the <code>useMemo</code> and <code>useCallback</code> hooks. You'll learn the difference between them and when to use each hook.</p>
<h2 id="heading-the-usememo-hook">The <code>useMemo</code> Hook</h2>
<p>The <code>useMemo</code> hook <em>memoizes</em> the return value of an expensive calculation between renders. Memoizing means storing the value as a cached value so that the value need not be calculated again (unless it's required).</p>
<p><code>useMemo</code> is a hook used for optimising the performance of your renders. Normally, when you declare a variable inside a component, it gets re-created on every render. If it stores the return value of a function, then the function gets called every time your component renders.</p>
<p>Normally, this wouldn't be a problem. But, what if the function is expensive? What if it takes a longer time to execute? Take the following example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    result += i;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">const</span> value = calculate();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment Count<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>When you click on 'Increment Count', it takes a few seconds to update the count state. This is because the <code>calculate</code> function runs every time a component re-renders after state change.</p>
<p>Now, imagine if there were multiple state variables in the component, each serving its own purpose. Each state update would cause a re-render and execute this expensive function.</p>
<p>These state variables could be completely unrelated to the expensive calculation performed, which would cause unnecessary delays. This would affect the performance of your website and could lead to a terrible user experience.</p>
<p><code>useMemo</code> can help you tackle this issue. Let's first understand its syntax:</p>
<pre><code class="lang-python">const value = useMemo(expensiveFunction, [...dependencyArray])
</code></pre>
<p>The <code>useMemo</code> hook should be declared at the top level of your component. It takes the following arguments:</p>
<ul>
<li><p><code>expensiveFunction</code> contains the expensive calculation you want to perform. If you have declared the function outside, pass the function reference only, without the brackets. You can also pass arrow functions directly.</p>
</li>
<li><p><code>dependencyArray</code> contains list of dependencies for the hook. The expensive function will be called only when one of these dependencies is updated. You can pass state variables or props that are dependent on this calculation. Any other state updates will not trigger the function.</p>
</li>
</ul>
<p>On the first render, <code>useMemo</code> returns the result of <code>expensiveFunction</code> and caches the result. During the subsequent renders, it will return the cached value if no dependencies have changed. If they change, then it will call the function again.</p>
<p>Let's use this in our case:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [dependentCount, setDependentCount] = useState(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> value = useMemo(calculate, [dependentCount]);

<span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>

    // ...

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setDependentCount(dependentCount + 1)}&gt;
      Increment Dependent Count
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Dependent Count: {dependentCount}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<p>We have created another state <code>dependentCount</code> that we assume is dependent on the expensive calculation. When this state updates and renders the component, the <code>calculate</code> function will run.</p>
<p>But if any other state changes, then <code>useMemo</code> will return the cached value instead of running the function again.</p>
<p>Let's test this by adding a <code>console.log</code> inside the function:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/image-28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output with useMemo</em></p>
<p>Now, when you click "Increment Count", the rendering is faster, since the <code>calculate</code> function is not getting called on every render. This is the same during every other state update not listed in the useMemo dependency array.</p>
<p>But when you click on "Increment dependent Count", it takes time to render the updated value. This is because <code>dependentCount</code> is a dependency of <code>useMemo</code> and changing it calls the expensive function, so the component takes time to re-render.</p>
<p>In this way, with <code>useMemo</code>, you can control the execution of an expensive function by calling it only for state updates that actually need the value returned. This can drastically improve your app's performance.</p>
<h3 id="heading-when-to-use-usememo">When to use <code>useMemo</code>:</h3>
<ul>
<li><p>When you have a state dependent on an expensive calculation, but you don't want to run the calculation on every render.</p>
</li>
<li><p>When you declare an array or object inside a component, its reference changes on every render, even though the value remains the same. Wrapping the values inside <code>useMemo</code> maintains referential equality and prevents unnecessary re-renders. This is essential when there's a <code>useEffect</code> dependent on the array or object.</p>
</li>
<li><p>When you are rendering lists using <code>Array.map</code> that do not need to change unless a certain state value changes.</p>
</li>
</ul>
<h2 id="heading-the-usecallback-hook">The <code>useCallback</code> Hook</h2>
<p>Similar to <code>useMemo</code>, you can also use this hook to optimise performance. The <code>useCallback</code> hook memoizes a callback function and returns it.</p>
<p>Note that the <code>useCallback</code> hook memoizes the function itself, not its return value. <code>useMemo</code> caches the functions return value so that the function need not execute again. <code>useCallback</code> caches the function definition or the function reference.</p>
<p>A function declared inside a component gets re-created on every component render, similar to a variable. The difference is, it gets rendered with a different reference every time. So, a <code>useEffect</code> dependent on this function will execute again on each render. A similar thing happens with child components.</p>
<p>Let's take an example:</p>
<pre><code class="lang-python">const App = () =&gt; {
  const [count, setCount] = useState(<span class="hljs-number">0</span>);
  const [value, setValue] = useState(<span class="hljs-string">""</span>);

  const handleClick = () =&gt; {
    setValue(<span class="hljs-string">"Kunal"</span>);
  };
  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">"App"</span>&gt;
      &lt;button onClick={() =&gt; setCount(count + <span class="hljs-number">1</span>)}&gt;Increment Count&lt;/button&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
      &lt;p&gt;Value: {value}&lt;/p&gt;
      &lt;SlowComponent handleClick={handleClick} /&gt;
    &lt;/div&gt;
  );
};

const SlowComponent = React.memo(({ handleClick, value }) =&gt; {

  // Intentially making the component slow
  <span class="hljs-keyword">for</span> (let i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {}

  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;h1&gt;Slow Component&lt;/h1&gt;
      &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;

    &lt;/div&gt;
  );
});
</code></pre>
<p>Here, we have a <code>SlowComponent</code> as the child of the <code>App</code> component. When a parent component renders, all of its child components render, regardless of whether anything has changed inside them.</p>
<p>To avoid unnecessary renders of the child components, we generally use the <code>React.memo</code> function. This basically caches the component and only re-renders it if its props have changed.</p>
<p>Now, when you click on 'Increment Count', it still takes a long time to render, because <code>SlowComponent</code> re-renders on state change. But why is that? We're not changing any of its props.</p>
<p>On the surface, we may not appear to change the value of <code>handleClick</code> prop. But, since functions are re-created with a different reference, on every render of the App component, its child (that is <code>SlowComponent</code>) renders.</p>
<p>To maintain referential equality, we wrap this function's definition inside a <code>useCallback</code>.</p>
<p>Let's understand its syntax:</p>
<pre><code class="lang-python">const cachedFn = useCallback(fn, [...dependencyArray])
</code></pre>
<p><code>useCallback</code> takes the following arguments:</p>
<ul>
<li><p><code>fn</code> is the function you want to cache. It is the function definition that you want to create, and can take any arguments and return any value.</p>
</li>
<li><p><code>dependencyArray</code> is a list of dependencies, changes to which trigger re-creation of the function. You can pass state values or props that are dependent on this function.</p>
</li>
</ul>
<p>On the first render, React creates the function (does not call it) and caches it. On the subsequent renders, the cached function is returned to you. Remember, this hook returns and caches the <em>function</em> and not its return value.</p>
<p>Let's use this hook in our example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

const App = () =&gt; {

  // ...

  const handleClick = useCallback(() =&gt; {
    setValue(<span class="hljs-string">"Kunal"</span>);
  }, [value, setValue]);

  // ...
};
</code></pre>
<p>Here, we have wrapped the function inside a <code>useCallback</code> and passed two dependencies that are involved with this function.</p>
<p>Now, when you click on 'Increment Count', the rendering is much faster. This is because the <code>handleClick</code> reference is cached between renders and hence, <code>SlowComponent</code> does not re-render.</p>
<p>But when you click on the button inside <code>SlowComponent</code> it will re-render. This is because when the <code>value</code> state changes, the <code>handleClick</code> method is created again and so the props of the slow component have changed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Value takes time to render</em></p>
<p>You can add many more states to the <code>App</code> component and update them without inhibiting performance as long as you don't update <code>value</code>'s state.</p>
<h3 id="heading-when-to-use-usecallback">When to use <code>useCallback</code></h3>
<ul>
<li><p>When you have event handlers defined for an element inside your component, wrap them inside a <code>useCallback</code> to avoid unnecessary re-creations of event handlers.</p>
</li>
<li><p>When you call a function inside a <code>useEffect</code>, you usually pass the function as a dependency. To avoid using <code>useEffect</code> unnecessarily on every render, wrap the function definition inside a <code>useCallback</code>.</p>
</li>
<li><p>If you are writing a custom hook, and it returns a function, it is recommended to wrap it inside a <code>useCallback</code>. So, there's no need for the users to worry about optimizing the hook – rather, they can focus on their own code.</p>
</li>
</ul>
<h2 id="heading-differences-between-usememo-and-usecallback">Differences Between <code>useMemo</code> and <code>useCallback</code></h2>
<p>Let's summarize the differences between the two hooks:</p>
<ul>
<li><p><code>useMemo</code> caches the return value of a function. <code>useCallback</code> caches the function definition itself.</p>
</li>
<li><p><code>useMemo</code> is used when you have an expensive calculation you want to avoid on every render.</p>
</li>
<li><p><code>useCallback</code> is used to cache a function to avoid re-creating it on every re-render.</p>
</li>
<li><p><code>useMemo</code> makes sure that an expensive function should only be called for state values dependent on it.</p>
</li>
<li><p><code>useCallback</code> creates stable functions that maintain the same reference between renders. This avoids unnecessary rendering of child components.</p>
</li>
</ul>
<p>And here are a few more things to remember. Use these hooks only if you want to memoize expensive calculations or prevent unnecessary re-renders. Do not use <code>useMemo</code> and <code>useCallback</code> everywhere.</p>
<p>For regular functions, these hooks don't make much difference. Overusing them will make your code unreadable. Instead, you can figure out other ways to improve app performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><code>useMemo</code> and <code>useCallback</code> are useful hooks in React that can help you optimize performance of your web app. It is important to understand the difference between the two and their usages.</p>
<p>In this article, we have discussed how both hooks work. <code>useMemo</code> caches the result of an expensive calculation, while <code>useCallback</code> caches the function reference. We also listed down scenarios when you should use each hook. Together, both these hooks can make your website faster.</p>
<p>I hope this article helps clear up any confusion. If you have further questions or comments regarding the post, reach out to me on Twitter. I would love to hear suggestions. Till next time, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Infinite Scrolling in React Using the Intersection Observer API ]]>
                </title>
                <description>
                    <![CDATA[ Hi fellow developers! Have you ever wondered how social media apps like Facebook and Instagram keep you scrolling endlessly through your feed? This user experience, designed to load new content on demand, uses a technique called infinite scrolling. T... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/infinite-scrolling-in-react/</link>
                <guid isPermaLink="false">66d85155bfb3c4f0b376afec</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 01 Jul 2024 09:24:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/photo-1563986768494-4dee2763ff3f.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi fellow developers! Have you ever wondered how social media apps like Facebook and Instagram keep you scrolling endlessly through your feed?</p>
<p>This user experience, designed to load new content on demand, uses a technique called infinite scrolling. This helps keep you hooked to these apps for hours.</p>
<p>Traditionally, these features would have you click "Next Page" to display new content. However, infinite scrolling reduces the load on the server by fetching less data at a time and thus, provides a much more engaging user experience.</p>
<p>In this post, we are going to implement the same feature in JavaScript. We'll use the Intersection Observer API to load data on demand, as the user is scrolling. We'll create a simple React application that displays posts similar to a social media feed.</p>
<h2 id="heading-how-to-set-up-the-react-app">How to Set Up the React App</h2>
<p>Run <code>create-react-app</code> in your terminal or use a <a target="_blank" href="https://www.freecodecamp.org/news/get-started-with-vite/">modern built tool like Vite</a> to create your React app. Remove the existing boilerplate code. There is no need to install any additional dependencies. Run <code>npm start</code> command to start the project.</p>
<p>You can find the complete code of this tutorial on <a target="_blank" href="https://github.com/KunalN25/my-tutorials/tree/main/javascript-and-react/infinite-scroll-js">GitHub</a>. Let's get started.</p>
<h2 id="heading-how-to-create-the-data-fetching-function">How to Create the Data Fetching Function</h2>
<p>Create a separate file called <code>services.js</code> and write the following data fetching function.</p>
<p>We'll use the <code>/posts</code> API from <a target="_blank" href="https://jsonplaceholder.typicode.com">JSONPlaceholder</a> to get our data.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> (page, limit) =&gt; {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(
    <span class="hljs-string">`https://jsonplaceholder.typicode.com/posts?_page=<span class="hljs-subst">${page}</span>&amp;_limit=<span class="hljs-subst">${limit}</span>`</span>
  );
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-keyword">return</span> data;
};
</code></pre>
<p>Here, we have passed two params to the API:</p>
<ul>
<li><p><code>page</code> indicates the part of data that is called. This increases each time the user scrolls and loads new data.</p>
</li>
<li><p><code>limit</code> indicates the amount of data that is called at a time. For infinite scrolling, we call just enough data that can be displayed on a single page.</p>
</li>
</ul>
<h2 id="heading-how-to-build-the-infinite-scroll-component">How to Build the Infinite Scroll Component</h2>
<p>Let's create a component <code>PostsList</code> for displaying a list of posts with infinite scrolling.</p>
<p>Let's create our state variables, fetch the data, and display it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> PostsList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [posts, setPosts] = useState([]);
  <span class="hljs-keyword">const</span> [page, setPage] = useState(<span class="hljs-number">1</span>);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Your Feed<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        {posts.map((post, index) =&gt; (
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span>
            <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.body}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        ))}
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<p>Here, we have defined the state variables for posts, page number and loading state. Note that the page number does not mean that we are adding pagination. It's just a parameter to load the next set of data.</p>
<p>Now, let's call our API with the current page number and set the loading states:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> loadMorePosts = <span class="hljs-keyword">async</span> () =&gt; {
    setLoading(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">const</span> newPosts = <span class="hljs-keyword">await</span> fetchPosts(page, <span class="hljs-number">10</span>);
    setPosts(<span class="hljs-function">(<span class="hljs-params">prevPosts</span>) =&gt;</span> [...prevPosts, ...newPosts]);
    setLoading(<span class="hljs-literal">false</span>);
  };

  useEffect(<span class="hljs-function">() =&gt;</span> {
    loadMorePosts();
  }, [page]);
</code></pre>
<p>Until now, we have fetched the initial 10 posts on first load of the page. We want to load more data as the user scrolls down the page.</p>
<p>Next, we'll use the Intersection Observer API to detect when additional data should be loaded.</p>
<p>Before using it, let's first understand what this API is.</p>
<h2 id="heading-what-is-the-intersection-observer-api">What is the Intersection Observer API?</h2>
<p>The Intersection Observer API is a web API that allows you to asynchronously observe changes in the intersection of a target element with an ancestor element or the viewport.</p>
<p>In simpler terms, it enables you to detect when an element enters or exits in an area of another DOM element or the viewport. Using Intersection Observer provides us with following advantages:</p>
<ul>
<li><p>Reduces the need for attaching event listeners to every scroll event.</p>
</li>
<li><p>Removes the need for manual calculations of the element's position and their event listeners, thus simplifying your code.</p>
</li>
<li><p>Efficient for observing multiple events compared to scroll or resize event listeners.</p>
</li>
</ul>
<p>Go through the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">MDN Docs</a> to understand more about Intersection Observer.</p>
<h2 id="heading-how-to-use-the-intersection-observer-api">How to Use the Intersection Observer API</h2>
<p>To use this API, we'll need to create an observer object.</p>
<p>Here's how you create an observer object:</p>
<pre><code class="lang-python">const observer = new IntersectionObserver(callback, options);
</code></pre>
<ul>
<li><p><code>callback</code> is a function called when the observed element's visibility changes. This function takes two arguments: <code>entries</code> and the <code>observer</code> object itself. Each object in <code>entries</code> array is an <code>IntersectionObserverEntry</code> object that contains information about the observed element's intersection status.</p>
</li>
<li><p><code>options</code> is an optional argument to further configure the Observer.</p>
</li>
</ul>
<p>How do we use this in our application? We'll define observer object as a ref:</p>
<pre><code class="lang-js">  <span class="hljs-keyword">const</span> observer = useRef();
</code></pre>
<p>Now, to set this observer object on an element and to detect whether that element is intersecting with the viewport, we use the following function, which is a callback ref:</p>
<pre><code class="lang-python">const lastPostElementRef = useCallback(
    (node) =&gt; {
      <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span>;
      <span class="hljs-keyword">if</span> (observer.current) observer.current.disconnect();

      observer.current = new IntersectionObserver((entries) =&gt; {
        <span class="hljs-keyword">if</span> (entries[<span class="hljs-number">0</span>].isIntersecting) {
          setPage((prevPage) =&gt; prevPage + <span class="hljs-number">1</span>); // trigger loading of new posts by chaging page no
        }
      });

      <span class="hljs-keyword">if</span> (node) observer.current.observe(node);
    },
    [loading]
  );
</code></pre>
<p>Let's understand how this function works:</p>
<ul>
<li><p>We check if the data is still loading. If it is, then we do not execute the logic.</p>
</li>
<li><p>To refer to the <code>observer</code> object, we use the ref's <code>current</code> property.</p>
</li>
<li><p>If an element is already being observed, then disconnect it and create a new Observer that changes the page number, thus triggering the API call if the observed element intersects with the viewport.</p>
</li>
<li><p>Since we are only observing one element at a time (such as the last element of the page) the size of <code>entries</code> is one.</p>
</li>
<li><p>This new Observer will now watch the current element to which the ref is attached to, which is the last element on the page.</p>
</li>
</ul>
<p>Since we only want to observe the last element on the page, we add this ref according to following condition:</p>
<pre><code class="lang-python">{posts.map((post, index) =&gt; (
          &lt;li
            key={post.id}
            ref={posts.length === index + <span class="hljs-number">1</span> ? lastPostElementRef : null}
          &gt;
            ...
          &lt;/li&gt;
        ))}
</code></pre>
<p>Now, why are we using callback refs instead of the <code>observer</code> ref itself?</p>
<p>A ref gives us a direct reference to the element and sets the value of the ref object directly. It works well for elements that do not need to change reference dynamically.</p>
<p>A callback ref offers more control over the ref and can handle dynamic changes to reference more effectively. It is a function called with the element's instance, or its DOM Node when the component mounts and with null if it unmounts.</p>
<p>In our case, our reference changes dynamically since our last element gets updated as more data is loaded. We are also able to write some logic to observe and disconnect from a node, while setting our ref object.</p>
<p>We'll also wrap the <code>lastPostElementRef</code> function inside a <code>useCallback</code> hook to avoid it getting re-created on every re-render. We'll only create this function if the loading state changes when it's time to execute the function.</p>
<p>Run your app with <code>npm start</code>, go to <code>http://localhost:3000</code>, and open the Network Tab. As you scroll down, you'll see new API requests being made as you scroll down the page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/image-101.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API requests for each new page</em></p>
<p>You can find the complete code on <a target="_blank" href="https://github.com/KunalN25/my-tutorials/tree/main/javascript-and-react/infinite-scroll-js">GitHub</a> and similar tutorials in JavaScript and React.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>When you implement infinite scrolling in your application, it provides a seamless and engaging user experience similar to what you see on popular social media apps. Instead of clicking through pages, users can effortlessly scroll through the content that loads dynamically.</p>
<p>In our example, we created a mock social media feed that loaded more content as the user scrolls down. We used the Intersection Observer API to detect the position of the last element according to which we loaded more data. It simplified our code and removed the need for attaching multiple event listeners.</p>
<p>I hope this helps you create similar features in your next web project and enables you to provide an engaging user experience. Please share your thoughts and feedback. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React 19 – New Hooks Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hi fellow readers! Web Development is a constantly evolving landscape. The whole ecosystem consists of different libraries and technologies. React is one of the most widely used libraries in web development. There are small releases every now and the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-19-new-hooks-explained-with-examples/</link>
                <guid isPermaLink="false">66d85162175544516f70c492</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Tue, 28 May 2024 12:56:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/thumb.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi fellow readers! Web Development is a constantly evolving landscape. The whole ecosystem consists of different libraries and technologies. React is one of the most widely used libraries in web development.</p>
<p>There are small releases every now and then. However, this year, the React team has made a significant announcement introducing a new version, React 19. On April 25, 2024, React officially released the beta version of React 19 to the public.</p>
<p>This version comes with a whole host of new features, along with new hooks. In this post, we are going to discuss four new hooks available in the new version:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-useformstatus">useFormStatus</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useactionstate">useActionState</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useoptimistic">useOptimistic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use">use</a></p>
</li>
</ul>
<h2 id="heading-existing-form-handling-implementation">Existing Form Handling Implementation</h2>
<p>Before going into the first hook, let's see how we currently implement form handling in React:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { submitAction } <span class="hljs-keyword">from</span> <span class="hljs-string">"./actions"</span>;

<span class="hljs-keyword">const</span> FormHandling = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [pending, setPending] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (event) =&gt; {
    event.preventDefault();
    setPending(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">await</span> submitAction({ name });
    setPending(<span class="hljs-literal">false</span>);
    setName(<span class="hljs-string">""</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your name"</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setName(e.target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      {pending &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Submitting {name}...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
};
</code></pre>
<p>Normally, we use state-controlled form to set the form data and use it to submit the same to the server with the <code>onSubmit</code> attribute of the form. Also, we use a <code>pending</code> state variable to handle submission pending states.</p>
<p>The next three hooks I have shown will change the way we handle forms.</p>
<h2 id="heading-useformstatus">useFormStatus</h2>
<p>The <code>useFormStatus</code> hook gives information about the form's status while submitting the form. This hook is part of the React DOM, so import it from <code>react-dom</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {useFormStatus} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>
</code></pre>
<p>This hook can be used in the following way:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> { pending, data } = useFormStatus();
</code></pre>
<p>The hook does not take any arguments and returns an object containing information about the form's status. It returns:</p>
<ul>
<li><p><code>pending</code>, which is a boolean value that indicates whether the form is in pending state.</p>
</li>
<li><p><code>data</code>, which is an object of type <code>[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)</code>, and contains the values of the form fields.</p>
</li>
</ul>
<p>This hook can only be used inside a component that has a</p>
<p>element as its parent. It only returns status information of the parent form element and not the <code>&lt;form&gt;</code> element rendered in the same component.</p>
<p>The following will not work:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {pending, data} = useFormStatus()
<span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">{submit}</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
</code></pre>
<p>Let's use the same previous form and write it in a separate component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { submitAction } <span class="hljs-keyword">from</span> <span class="hljs-string">"../../actions"</span>;
<span class="hljs-keyword">import</span> { useFormStatus } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom"</span>;

<span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { pending, data } = useFormStatus();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your name"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{pending}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>
        Submit
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      {pending &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Submitting {data?.get("username")}...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> FormStatusWithHooks = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>
      <span class="hljs-attr">action</span>=<span class="hljs-string">{async</span> () =&gt;</span> {
        await submitAction();
      }}
    &gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
};
</code></pre>
<p>Here, instead of using <code>onSubmit</code>, we are using the action prop of the form element. And we have used the <code>data</code> object to access the form fields and render them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731049965919/b3e23267-8d1b-4d76-b996-8c7d965b96a5.png" alt="b3e23267-8d1b-4d76-b996-8c7d965b96a5" class="image--center mx-auto" width="890" height="344" loading="lazy"></p>
<p><em>Rendering form data with pending state</em></p>
<p>You can use any number of forms inside the parent <code>&lt;form&gt;</code> element and get the form state with <code>useFormStatus</code> hook. So, you do not need to implement the same logic every time. This improves reusability in the code.</p>
<h2 id="heading-useactionstate">useActionState</h2>
<p><code>useActionState</code> can be used in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state, formAction] = useActionState(submitData, initialState);
</code></pre>
<p>It takes the following parameters:</p>
<ul>
<li><p><code>submitData</code>, which is the function that is called when form is submitted. This function should take two parameters: the current state and a FormData object.</p>
</li>
<li><p><code>initialState</code>, which is the initial value of the state when the form is not submitted.</p>
</li>
</ul>
<p>It returns an array with following:</p>
<ul>
<li><p><code>state</code>, which is the current state that is being rendered in the component. This state is equal to the initial state.</p>
</li>
<li><p><code>formAction</code>, which is the new action that you can pass to the action prop of your form element. This executes the action that you passed with the current state and returns a new, updated state.</p>
</li>
</ul>
<p>Let's understand how to use the hook with the following form:</p>
<pre><code class="lang-javascript">&lt;form action={formAction}&gt;
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your name"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter age"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    &lt;/form&gt;
</code></pre>
<p>This form submits user information, name and age, which is appended to a list of users stored as state. Let's use the <code>useActionState</code> hook to get the state:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useActionState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { submitActionWithCurrentState } <span class="hljs-keyword">from</span> <span class="hljs-string">"../../actions"</span>;
<span class="hljs-keyword">const</span> ActionStateComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [state, formAction] = useActionState(submitActionWithCurrentState, {
    <span class="hljs-attr">users</span>: [],
    <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>,
  });

<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">{formAction}</span>&gt;</span>...<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
</code></pre>
<p>The <code>submitActionWithCurrentState</code> method returns a new state consisting of the modified users list and gives an error if a user with the given name already exists. Let's render the list of users and error (if any):</p>
<pre><code class="lang-javascript">&lt;div className=<span class="hljs-string">"error"</span>&gt;{state?.error}&lt;/div&gt;
      {state?.users?.map(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.username}</span>&gt;</span>
          Name: {user.username} Age: {user.age}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
      ))}
</code></pre>
<p>After you submit the form, the component re-renders and updates the state in the component.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050034809/e30a20be-aca2-4973-99ba-8cc6192657bb.png" alt="e30a20be-aca2-4973-99ba-8cc6192657bb" class="image--center mx-auto" width="1176" height="450" loading="lazy"></p>
<p><em>List of submitted users stored as state</em></p>
<p>If you try to submit an existing user name you get an error:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050059494/a5d51224-c6e4-43eb-b2ae-0ee4059d0b54.png" alt="a5d51224-c6e4-43eb-b2ae-0ee4059d0b54" class="image--center mx-auto" width="1230" height="442" loading="lazy"></p>
<p><em>Error if user already exists</em></p>
<h2 id="heading-useoptimistic">useOptimistic</h2>
<p>As the name suggests, <code>useOptimistic</code> optimistically updates the UI while an async operation is still underway. When a user submits a form that changes a piece of UI, this hook can "optimistically" show the expected result while the form is still submitting.</p>
<ul>
<li><p>If the form submission is successful, the UI remains the same.</p>
</li>
<li><p>If the form submission fails, the UI reverts back to the previous state.</p>
</li>
</ul>
<p>This allows you to immediately update the UI even if the form submission takes time:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [optimisticState, setOptimisticState] = useOptimistic(actualState, updateFn);
</code></pre>
<p>The <code>useOptimistic</code> hook takes the following parameters:</p>
<ul>
<li><p><code>actualState</code>, which is the value of the optimistic state when no action is pending.</p>
</li>
<li><p><code>updateFn</code> (optional), which is a function that takes the actual state and the value passed to the <code>setOptimisticState</code> method and calculates the optimisticState. If this parameter is not specified, the optimistic state is equal to the new value.</p>
</li>
</ul>
<p>It returns the following:</p>
<ul>
<li><p><code>optimisticState</code>, which is the optimistic (temporary) value shown while the action is pending.</p>
</li>
<li><p><code>setOptimisticState</code>, which is a function that sets the optimistic state to a new value.</p>
</li>
</ul>
<p>Let's have a form that performs an async operation to change the title of the page:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useOptimistic, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> OptimisticComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">"Title"</span>);
  <span class="hljs-keyword">const</span> [optimisticTitle, setOptimisticTitle] = useOptimistic(title);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> pending = title !== optimisticTitle;
  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (formData) =&gt; {

  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{optimisticTitle}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> {pending &amp;&amp; "Updating..."} <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"title"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Change Title"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{pending}</span>&gt;</span>
          Submit
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error"</span>&gt;</span>{error &amp;&amp; error}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<p>In the code above:</p>
<ul>
<li><p>We are displaying the optimistic value of the title, which is set to <code>title</code> state when no action is pending.</p>
</li>
<li><p>We have defined a pending variable that is set to true if the current and optimistic state do not match. Depending on this, we display a pending text and disable the button.</p>
</li>
<li><p>We display an error in case the async operation throws an error.</p>
</li>
</ul>
<p>Now, let's call our async function that either resolves or rejects our request:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { submitTitle } <span class="hljs-keyword">from</span> <span class="hljs-string">"../../actions"</span>;

<span class="hljs-keyword">const</span> OptimisticComponent = <span class="hljs-function">() =&gt;</span> {

  ...

  const handleSubmit = <span class="hljs-keyword">async</span> (formData) =&gt; {
    setError(<span class="hljs-literal">null</span>);
    setOptimisticTitle(formData.get(<span class="hljs-string">"title"</span>));
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> updatedTitle = <span class="hljs-keyword">await</span> submitTitle(formData);
      setTitle(updatedTitle);
    } <span class="hljs-keyword">catch</span> (e) {
      setError(e);
    }
  };

  ...

};
</code></pre>
<p>In the code above:</p>
<ul>
<li><p>We have updated the states as we originally did.</p>
</li>
<li><p>Before calling the async operation, we set the optimistic state to the updated title we just submitted.</p>
</li>
<li><p>If the promise rejects, the optimistic state reverts back to the original one, so no need to set it again.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050097373/a130fbe2-f3b4-4073-9330-4e38de8dfb4c.png" alt="a130fbe2-f3b4-4073-9330-4e38de8dfb4c" class="image--center mx-auto" width="1304" height="538" loading="lazy"></p>
<p><em>Title Updating optimistically</em></p>
<h2 id="heading-use">use</h2>
<p>The <code>use</code> method has not been released as a hook, but as part of the React API. Unlike React hooks, <code>use</code> can also be called inside <code>if</code> and <code>for</code> statements. However, <code>use</code> can only be called inside a Component or a Hook.</p>
<p><code>use</code> lets you read the value of a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> or a <a target="_blank" href="https://react.dev/learn/passing-data-deeply-with-context">Context</a> inside a component. Let's understand its usage in reading both context and promise.</p>
<h4 id="heading-reading-contexts">Reading contexts</h4>
<p>In case of contexts, <code>use</code> works similar to the <a target="_blank" href="https://react.dev/reference/react/useContext"><code>useContext</code></a> hook. It returns the value provided by the context to be used inside the component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createContext, use } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../../styles.css"</span>;

<span class="hljs-keyword">const</span> ThemeContext = createContext(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> UseHookWithContext = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">"dark"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> theme = use(ThemeContext);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">myContainer</span> <span class="hljs-attr">theme-</span>${<span class="hljs-attr">theme</span>}`}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Hi There!<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<p>The code above gives the following output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050125728/19276d93-21ad-4694-8eb0-3f5f517235a7.png" alt="19276d93-21ad-4694-8eb0-3f5f517235a7" class="image--center mx-auto" width="1412" height="662" loading="lazy"></p>
<p><em>Dark Theme</em></p>
<p>Unlike <code>useContext</code>, <code>use</code> provides more flexibility since it can also be used conditionally using <code>if</code> statements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> CodeSnippet = <span class="hljs-function">(<span class="hljs-params">{canShow}</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(canShow) {
        <span class="hljs-keyword">const</span> theme = use(ThemeContext)
        <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Code snippet shown with {theme} theme <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}
</code></pre>
<h4 id="heading-reading-resolved-values-of-promises">Reading resolved values of promises</h4>
<p><code>use</code> returns the resolved value of the promise to be used inside the component. It integrates with the <a target="_blank" href="https://react.dev/reference/react/Suspense">Suspense</a> API to display a temporary message till a promise is resolved.</p>
<p>Let's have a client component with a promise passed down as a prop from a server component:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"use client"</span>;

<span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { ErrorBoundary } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-error-boundary"</span>;

<span class="hljs-keyword">const</span> DataContainer = <span class="hljs-function">(<span class="hljs-params">{ dataPromise }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">p</span>&gt;</span>Fetching Data...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">DataComponent</span> <span class="hljs-attr">dataPromise</span>=<span class="hljs-string">{dataPromise}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> DataComponent = <span class="hljs-function">(<span class="hljs-params">{ dataPromise }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = use(dataPromise);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{data &amp;&amp; data}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};
</code></pre>
<p>In the code above:</p>
<ul>
<li><p>The promise created in a server component is passed down to client component as a prop. This in turn, can be passed to the <code>use</code> method. This allows the client component to read the resolved value of the promise.</p>
</li>
<li><p>The <code>Suspense</code> API renders the element passed to the <code>fallback</code> prop while the promise is still pending.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050154298/a5cc1b8f-63ba-400f-b42e-df1da7a81b3c.png" alt="a5cc1b8f-63ba-400f-b42e-df1da7a81b3c" class="image--center mx-auto" width="1412" height="662" loading="lazy"></p>
<p><em>Data shown on button click</em></p>
<p>In case a promise rejects, there are two ways to display an error to the users:</p>
<ol>
<li>Returning an error message in the <code>catch</code> block of the promise and treating it as a resolved promise:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    ...
    <span class="hljs-comment">// ...</span>

  }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> err);
}
</code></pre>
<ol start="2">
<li>Wrapping the component with an <a target="_blank" href="https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary">ErrorBoundary</a>:</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731050189144/2aa97ad6-0da9-4ee2-8ba1-5770d8e66156.png" alt="2aa97ad6-0da9-4ee2-8ba1-5770d8e66156" class="image--center mx-auto" width="488" height="316" loading="lazy"></p>
<p><em>Error Boundary rendered when Promise rejected</em></p>
<p>You can find the complete code in the CodeSandbox <a target="_blank" href="https://codesandbox.io/p/sandbox/gracious-haslett-4qdzn4?file=%2Fsrc%2Findex.js&amp;from-embed=">here</a>. Feel free to fork it and play around.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codesandbox.io/embed/4qdzn4?view=preview&amp;module=%2Fsrc%2FApp.js" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodeSandbox embed" allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" loading="lazy"></iframe></div>
<p> </p>
<p>This is not the end. React 19 has a lot more to offer. You can check out all the new features in the <a target="_blank" href="https://react.dev/blog/2024/04/25/react-19">docs</a>.</p>
<p>Currently, React 19 is still in beta version, so do not use it for production systems yet. However, you can install React 19 canary version by adding the following dependencies in your <code>package.json</code> file and running <code>npm i</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"react"</span>: <span class="hljs-string">"canary"</span>,
    <span class="hljs-string">"react-dom"</span>: <span class="hljs-string">"canary"</span>,
  },
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The React Team has introduced several useful hooks that will improve convenience for developers.</p>
<p>The first three hooks: <code>useFormStatus</code>, <code>useActionState</code>, and <code>useOptimistic</code> change the way we handle forms. The <code>use</code> hook makes it really convenient to get the resolved value of a promise inside a component.</p>
<p>In this post, I have explained the syntax of each hook and demonstrated their usage examples. This would surely help you to understand these hooks and how to use them. I hope this helps you in your future projects.</p>
<p>If you have any questions or need further clarification, let me know. Your feedback is always valued and appreciated! Connect with me on Twitter for more updates and discussions. Thank you for reading, and I look forward to seeing you next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript Interview Prep Handbook – Essential Topics to Know + Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a widely used language in web development and powers interactive features of virtually every website out there. JavaScript makes it possible to create dynamic web pages and is very versatile. JavaScript remains one of the most in-demand... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/js-interview-prep-handbook/</link>
                <guid isPermaLink="false">66d8515ef01807d1f69107df</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Wed, 22 May 2024 09:58:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/JavaScript-Interview-Prep-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a widely used language in web development and powers interactive features of virtually every website out there. JavaScript makes it possible to create dynamic web pages and is very versatile.</p>
<p>JavaScript remains one of the most in-demand programming languages in 2024. Many companies are looking for proficiency in JavaScript, and one of its frameworks like Angular and React. If you are an aspiring web developer, understanding what these companies look for in interviews is the key to unlocking great opportunities.</p>
<p>In this handbook, I'll delve into several essential JavaScript concepts that you must prepare before going to an interview. Equipped with the fundamentals and the following concepts, you'll position yourself as an impressive candidate in the web development landscape.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-var-let-and-const-keywords">How to Use <code>var</code>, <code>let</code>, and <code>const</code> Keywords.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-hoisting">What is Hoisting?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-closures-work">How Do Closures Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-debouncing">How to Implement Debouncing.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-throttling">How to Implement Throttling.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-currying">What is Currying?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-difference-between-and">What is the Difference between <code>==</code> and <code>===</code>?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-the-this-keyword-work">How Does the <code>this</code> Keyword Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-call-apply-and-bind-methods">How to Use the <code>call</code>, <code>apply</code> and <code>bind</code> Methods.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-prototypes-and-prototypal-inheritance">What are Prototypes and Prototypal Inheritance?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-spread-operator">‌How to Use the Spread Operator.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-array-and-object-destructuring-work">How Does Array and Object Destructuring Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-promises">What are Promises?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-async-and-await-keywords">How to Use the <code>async</code> and <code>await</code> Keywords.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-an-event-loop">What is an Event Loop?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-event-propagation-works-bubbling-and-capturing">How Event Propagation Works – Bubbling and Capturing.</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-generator-functions">What are Generator Functions?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-polyfills-for-arraymap-arrayreduce-and-arrayfilter">How to Implement Polyfills for <code>Array.map()</code>, <code>Array.reduce()</code>, and <code>Array.filter()</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-thoughts">Additional Thoughts</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-var-let-and-const-keywords">How to Use <code>var</code>, <code>let</code>, and <code>const</code> Keywords</h2>
<p>In JavaScript, you can declare a variable in three ways: using <code>var</code>, <code>let</code> and <code>const</code>. It's essential to understand the difference between these three.</p>
<p>A <code>var</code> variable has global and function level scope. If the variable is declared globally, it can be accessed anywhere and if declared inside a function, it can be accessed anywhere within the function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a=<span class="hljs-number">5</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> b=<span class="hljs-number">4</span>
}

<span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// throws ReferenceError</span>
</code></pre>
<p>A <code>let</code> variable has block level scope. This variable, if declared inside a block, cannot be accessed outside it. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">if</span> (a &gt; <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">var</span> b = <span class="hljs-number">6</span>;
    <span class="hljs-keyword">let</span> c = <span class="hljs-number">7</span>;
}
<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// prints 5</span>
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// prints 6</span>
<span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// throws ReferenceError</span>
</code></pre>
<p>Here, variables <code>a</code> and <code>b</code> have global scope, so they can be accessed anywhere. Variable <code>c</code> cannot be accessed outside the <code>if</code> block since <code>let</code> only has block level scope.</p>
<p><code>const</code> is used to declare a constant. Once a variable is declared with <code>const</code>, it cannot be modified.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> x = <span class="hljs-number">5</span>;
x = <span class="hljs-number">6</span>; <span class="hljs-comment">// Throws an error</span>
</code></pre>
<p>However, you can modify properties of an object, or elements of an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'kunal'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">21</span> };
obj.name = <span class="hljs-string">'alex'</span>;
<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// { name: 'alex', age: 21 }</span>

<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4</span>;
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [ 1, 4, 3 ]</span>
</code></pre>
<h2 id="heading-what-is-hoisting">What is Hoisting?</h2>
<p>Hoisting refers to JavaScript's default behavior that moves all variables and function declarations to the top. This means you can use them before they are declared.</p>
<pre><code class="lang-javascript">x=<span class="hljs-number">5</span> 
<span class="hljs-built_in">console</span>.log(x) <span class="hljs-comment">// prints 5 </span>
<span class="hljs-keyword">var</span> x
</code></pre>
<p>In the code above, JavaScript has moved the variable declaration to the top of the code block. That is: it is similar to declaring <code>x</code> at the first line.</p>
<p>In the case of functions, the declarations are also moved to top:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"foo called"</span>);
}

foo(); <span class="hljs-comment">// foo called</span>
</code></pre>
<p>However, this does not work with <code>let</code> and <code>const</code>.</p>
<pre><code class="lang-javascript">x = <span class="hljs-number">5</span>; <span class="hljs-comment">// throws ReferenceError</span>
<span class="hljs-keyword">let</span> x;

fiz(); <span class="hljs-comment">// throws ReferenceError</span>
<span class="hljs-keyword">const</span> fiz = <span class="hljs-function">() =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"fiz called"</span>) };
</code></pre>
<h2 id="heading-how-do-closures-work">How Do Closures Work?</h2>
<p>Closures are an important concept in JavaScript. When you have a function inside another function, the inner function has access to all the variables of the outer function.</p>
<p>But when this inner function is returned by the outer function, the inner function can be called anywhere outside the outer function and it can still access those variables.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        count++;
        <span class="hljs-built_in">console</span>.log(count);
    };
}

<span class="hljs-keyword">const</span> innerFun = fun();
innerFun(); <span class="hljs-comment">// prints 1</span>
innerFun(); <span class="hljs-comment">// prints 2</span>
innerFun(); <span class="hljs-comment">// prints 3</span>
</code></pre>
<p>Here, <code>fun()</code> declares and initializes a variable <code>count</code>. Then, it returns an inner function that increments <code>count</code> before printing it. Now, when you call <code>innerFun()</code> anywhere outside the <code>fun()</code> method, it can still access <code>count</code> and increment it.</p>
<p>This is the concept of closures. You can understand more about closures in the following post by <a target="_blank" href="https://www.freecodecamp.org/news/author/matias-hernandez/">Matías Hernández</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/closures-in-javascript/">https://www.freecodecamp.org/news/closures-in-javascript/</a></div>
<p> </p>
<h2 id="heading-how-to-implement-debouncing">How to Implement Debouncing</h2>
<p>Debouncing is a technique that delays a function call by few seconds and ensures that there is always a delay between function call and execution.</p>
<p>When you call a function, it gets executed after a delay. However, if you call the function again within that delay, the previous call is cancelled and a new timer is started. The same process repeats for each subsequent function call.</p>
<p>Let's see how to implement it:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">debounce</span>(<span class="hljs-params">func, delay</span>) </span>{
    <span class="hljs-keyword">let</span> timeout = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (timeout) <span class="hljs-built_in">clearTimeout</span>(timeout);
        timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            func(...args);
            timeout = <span class="hljs-literal">null</span>;
        }, delay);
    };
}
</code></pre>
<p>Debouncing takes a function and a delay as parameters, and returns a new, debounced function. When you call the debounced function, it will execute after <code>delay</code> milliseconds. If the function is called within that time, it cancels the previous call and waits for <code>delay</code> again.</p>
<p>Let's test this behavior:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is a function with arguments <span class="hljs-subst">${a}</span> and <span class="hljs-subst">${b}</span>`</span>);
}

<span class="hljs-keyword">const</span> debouncedFun = debounce(fun, <span class="hljs-number">500</span>);
debouncedFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
debouncedFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
debouncedFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// This is a function with arguments 2 and 3</span>
</code></pre>
<p>The first two calls do not execute, while the third one does, after 500ms. Debouncing uses the concept of closures, so it's important to understand them first.</p>
<p>Debouncing has plenty of applications, with the most popular one being the auto-complete functionality in search bars. I have explained debouncing in detail in the following post:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/deboucing-in-react-autocomplete-example/">https://www.freecodecamp.org/news/deboucing-in-react-autocomplete-example/</a></div>
<p> </p>
<h2 id="heading-how-to-implement-throttling">How to Implement Throttling</h2>
<p>Throttling is a technique that limits the rate at which a function is called. A throttled function executes for the first time and can only be called again after a certain delay. If it is called within the delay, nothing happens.</p>
<p>Let's see how to implement it:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
    <span class="hljs-keyword">let</span> timeout = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!timeout) {
            func(...args);
            timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
                timeout = <span class="hljs-literal">null</span>;
            }, delay);
        }
    };
}
</code></pre>
<p><code>throttle()</code> takes a function and a delay as parameters, and returns a throttled function. When you call the throttled function, it executes the first time and starts a timeout with <code>delay</code>. Within this time, no matter how many times you call the throttled function, it won't execute.</p>
<p>Let's test this behavior:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is a function with arguments <span class="hljs-subst">${a}</span> and <span class="hljs-subst">${b}</span>`</span>);
}

<span class="hljs-keyword">const</span> throttledFun = throttle(fun, <span class="hljs-number">500</span>);

throttledFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// This is a function with arguments 2 and 3</span>
throttledFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    throttledFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
}, <span class="hljs-number">300</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    throttledFun(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// This is a function with arguments 2 and 3</span>
}, <span class="hljs-number">600</span>);
</code></pre>
<p>Here, the first call executes immediately, and for the next 500ms, no function call will execute. The last one executes since it is called after 500ms.</p>
<p>Throttling also uses the concept of closures. I have explained throttling in detail in my post, so check it out:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/throttling-in-javascript/">https://www.freecodecamp.org/news/throttling-in-javascript/</a></div>
<p> </p>
<h2 id="heading-what-is-currying">What is Currying?</h2>
<p>Currying is a technique where a function with multiple arguments is transformed into a sequence of functions, with each function taking a single argument and returning another function. For example, consider the function below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b, c</span>) </span>{
    <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>With currying, the above function can be written as:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">curryAdd</span>(<span class="hljs-params">a</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">b</span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">c</span>) </span>{
            <span class="hljs-keyword">return</span> a + b + c;
        };
    };
}
</code></pre>
<p>Here, each function inside <code>curryAdd</code> takes one argument and returns another function till all arguments are collected. <code>curryAdd</code> is also known as a <a target="_blank" href="https://www.freecodecamp.org/news/higher-order-functions-explained/">higher-order function</a>.</p>
<p>Currying allows you to reuse partial implementations of a function. In case you do not have all the arguments available, you can fix some arguments of the function initially and return a reusable function.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Reusable function</span>
<span class="hljs-keyword">const</span> addTwo = curryAdd(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(addTwo); <span class="hljs-comment">// prints the function</span>

<span class="hljs-comment">// Calling final result</span>
<span class="hljs-keyword">const</span> result1 = addTwo(<span class="hljs-number">5</span>)(<span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(result1); <span class="hljs-comment">// 17</span>

<span class="hljs-keyword">const</span> result2 = addTwo(<span class="hljs-number">3</span>)(<span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(result2); <span class="hljs-comment">// 10</span>
</code></pre>
<p><code>addTwo</code> is a reusable function that can be used later, when additional arguments become available.</p>
<p>Thus, currying enhances code modularity and flexibility with partial function application. It also allows you to create functions that are tailored to specific needs as seen in the example above.</p>
<p>Currying simplifies complex functions by breaking them down into simpler, more manageable parts. This leads to cleaner and readable code.</p>
<h2 id="heading-what-is-the-difference-between-and">What is the Difference between <code>==</code> and <code>===</code>?</h2>
<p>This is really simple, yet a very commonly asked in interviews.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">"1"</span>;

<span class="hljs-built_in">console</span>.log(a == b); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(a === b); <span class="hljs-comment">// false</span>
</code></pre>
<ul>
<li><p><code>==</code> compares only the value of <code>a</code> and <code>b</code>,</p>
</li>
<li><p><code>===</code> compares both value and data type of <code>a</code> and <code>b</code></p>
</li>
</ul>
<h2 id="heading-how-does-the-this-keyword-work">How Does the <code>this</code> Keyword Work?</h2>
<p>The <code>this</code> keyword is the object that you are currently referencing. Its value is set to the context in which you are using it. When referenced globally, <code>this</code> refers to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> object.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>) <span class="hljs-comment">// prints window {}</span>
</code></pre>
<p><code>this</code> can be used to access properties of an object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'kunal'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">21</span>,
    getInfo() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Name: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, Age: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span>`</span>);
    }
};

obj.getInfo();
</code></pre>
<p>Refer to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">docs</a> to learn more about the <code>this</code> keyword.</p>
<h2 id="heading-how-to-use-the-call-apply-and-bind-methods">How to Use the <code>call</code>, <code>apply</code> and <code>bind</code> Methods</h2>
<p>When you use <code>this</code> inside a function, its value is set to the object on which the function is called. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getInfo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Name: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, Age: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span>`</span>);
}
</code></pre>
<p><code>call</code>, <code>apply</code> and <code>bind</code> are used to set the value of the <code>this</code> keyword inside a method.</p>
<h3 id="heading-call"><code>call</code></h3>
<p>To call <code>getInfo()</code> function on an object, use the <code>call</code> function. Let's create two objects and call <code>getInfo()</code> on these objects.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ob1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'alex'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> };
<span class="hljs-keyword">const</span> ob2 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'marcus'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span> };

getInfo.call(ob1); <span class="hljs-comment">// Name: alex, Age: 25</span>
getInfo.call(ob2); <span class="hljs-comment">// Name: marcus, Age: 23</span>
</code></pre>
<p><code>call</code> sets the value of the <code>this</code> keyword inside a function.</p>
<h3 id="heading-apply"><code>apply</code></h3>
<p>The <code>apply</code> method is similar to <code>call</code>, but it differs in the way you pass arguments. Consider a function with arguments:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getInfo</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Name: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, Age: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span>`</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Args: <span class="hljs-subst">${a}</span> and <span class="hljs-subst">${b}</span>`</span>);
}

<span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'alex'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
};

getInfo.call(obj, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
getInfo.apply(obj, [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);
</code></pre>
<h3 id="heading-bind"><code>bind</code></h3>
<p><code>bind</code> is used to create a new function that has its <code>this</code> keyword set to one object. Let's use the above <code>getInfo</code> function as example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'alex'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
};

<span class="hljs-keyword">const</span> objGetInfo = getInfo.bind(obj, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
objGetInfo();
</code></pre>
<p>When <code>bind</code> is called on <code>getInfo()</code> function, it returns a new function that is bound to <code>obj</code>. Now, every time you call the <code>objGetInfo()</code> function, <code>this</code> keyword refers to <code>obj</code>.</p>
<p>All three methods are similar. That is, they set the value of <code>this</code> keyword. However, a key difference in <code>bind</code> is that it returns a new function, whereas <code>call</code> and <code>apply</code> simply just call the function.</p>
<h2 id="heading-what-are-prototypes-and-prototypal-inheritance">What are Prototypes and Prototypal Inheritance?</h2>
<p>Inheritance is a concept in object oriented programming that allows an object to inherit properties and methods from another object. However, inheritance works differently in JavaScript.</p>
<p>In JavaScript, every object has a property that links to another object called a prototype. The prototype itself is an object that can have its own prototype, thus forming a prototype chain. This chain ends when we reach a prototype equal to <code>null</code>.</p>
<p>Prototype allows you to inherit methods and properties from another object. When a property does not exist on an object, JavaScript searches its prototype and so on till it reaches the end of the prototype chain.</p>
<p>Let's understand with an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> animal = {
    <span class="hljs-attr">eats</span>: <span class="hljs-literal">true</span>,
    walk() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Animal is walking"</span>);
    }
};

<span class="hljs-keyword">const</span> rabbit = <span class="hljs-built_in">Object</span>.create(animal);
rabbit.jumps = <span class="hljs-literal">true</span>;
rabbit.walk(); <span class="hljs-comment">// Animal is walking</span>
</code></pre>
<p><code>Object.create</code> creates a new object <code>rabbit</code> with its prototype set to <code>animal</code>. You can also set additional properties of the new object.</p>
<p>Also, the <code>walk()</code> method does not exist on <code>rabbit</code>, so it searches the object's prototype <code>animal</code>. This means the <code>rabbit</code> object has inherited the properties and methods of the <code>animal</code> object.</p>
<p>You can also use the ES6 <code>Object.setPrototypeOf</code> method on any object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dog = {
    bark() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Dog barking"</span>);
    }
};

<span class="hljs-built_in">Object</span>.setPrototypeOf(dog, animal);
<span class="hljs-built_in">console</span>.log(dog.eats); <span class="hljs-comment">// true</span>
dog.walk(); <span class="hljs-comment">// Animal is walking</span>
</code></pre>
<p>You can also use a function as a constructor and set its prototype using the <code>prototype</code> property.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}

Animal.prototype.walk = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is walking`</span>);
};

<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">"Dog"</span>);
<span class="hljs-built_in">console</span>.log(dog); <span class="hljs-comment">// Animal { name: 'Dog' }</span>
dog.walk(); <span class="hljs-comment">// Dog is walking</span>
</code></pre>
<p>You can learn more about prototypes and inheritance in JavaScript in the following post by <a target="_blank" href="https://www.freecodecamp.org/news/author/gercocca/">Germán Cocca</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/prototypes-and-inheritance-in-javascript/">https://www.freecodecamp.org/news/prototypes-and-inheritance-in-javascript/</a></div>
<p> </p>
<h2 id="heading-how-to-use-the-spread-operator">‌How to Use the Spread Operator</h2>
<p>The spread operator is used to spread out contents of an array or object into individual elements or collect a bunch of elements into a single object. It has following use cases:</p>
<p>Spread operator can be used to copy an array into a new one:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> arr2 = [...arr1];

<span class="hljs-built_in">console</span>.log(arr1); <span class="hljs-comment">// [2, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(arr2); <span class="hljs-comment">// [2, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(arr1 == arr2); <span class="hljs-comment">// false</span>
</code></pre>
<p><code>arr1</code> and <code>arr2</code> are completely different objects as shown with the equality operator.</p>
<p>You can also reuse fields from one object while creating a new object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'kunal'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span> };
<span class="hljs-keyword">const</span> obj2 = { ...obj1, <span class="hljs-attr">gender</span>: <span class="hljs-string">'male'</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">'Mumbai'</span> };

<span class="hljs-built_in">console</span>.log(obj2); <span class="hljs-comment">// { name: 'kunal', age: 23, gender: 'male', city: 'Mumbai' }</span>
</code></pre>
<p>You can collect multiple arguments passed to a function into an array.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">console</span>.log(args);
}

fun1(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// [ 1, 2, 3, 4, 5 ]</span>
</code></pre>
<p>Or you can pass elements of an array as individual arguments to a function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun2</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${a}</span> and <span class="hljs-subst">${b}</span>`</span>);
}

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>];
fun2(...numbers);
</code></pre>
<h2 id="heading-how-does-array-and-object-destructuring-work">How Does Array and Object Destructuring Work?</h2>
<p>Similar to the spread operator, you can spread out elements of an array or an object into individual variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> [a, b, c] = arr;

<span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 3</span>
</code></pre>
<p>This is the same for objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'kunal'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">gender</span>: <span class="hljs-string">'male'</span> };
<span class="hljs-keyword">const</span> {name, age, gender} = obj;

<span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// kunal</span>
<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// 22</span>
<span class="hljs-built_in">console</span>.log(gender); <span class="hljs-comment">// male</span>
</code></pre>
<h2 id="heading-what-are-promises">What are Promises?</h2>
<p>Promises are a very important concept in JavaScript, almost certain to be asked in interviews. Promises are used for asynchronous operations in JavaScript like timeouts or API calls.</p>
<p>Promises use a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> object that exists in one of three states: pending, fulfilled (resolved), and rejected. When an asynchronous operation ends, a promise can either be resolved (successful) or rejected (failure).</p>
<p>Let's take a simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncOperation</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span> + <span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">10</span>;
        <span class="hljs-keyword">if</span> (x &lt; <span class="hljs-number">5</span>) 
            resolve(<span class="hljs-string">"Successful"</span>);
        <span class="hljs-keyword">else</span> 
            reject(<span class="hljs-string">"Error"</span>);
    });
}
</code></pre>
<p>The above function returns a promise that performs an asynchronous operation.</p>
<ul>
<li><p>If the operation is successful, the <code>resolve</code> method is called to indicate that the promise has been fulfilled.</p>
</li>
<li><p>If the operation fails, the <code>reject</code> method is called to indicate that the promise has been rejected.</p>
</li>
</ul>
<p>In this example, these methods are called at random. To handle this promise in your code, use the <code>then</code> and <code>catch</code> methods.</p>
<pre><code class="lang-javascript">asyncOperation()
    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(res);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(err);
    });
</code></pre>
<ul>
<li><p>The <code>then</code> method takes a callback function that executes if the promise was resolved. It takes a response object as an argument that is equal to the object you pass in the <code>resolve</code> method.</p>
</li>
<li><p>The <code>catch</code> method takes a callback function that executes if the promise was rejected and takes an error object as argument that is passed in the <code>reject</code> method.</p>
</li>
</ul>
<p>The above code prints "Successful" and "Error" at random.</p>
<p>Apart from the basics, the Promise object also contains useful methods that work with multiple promises: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all()</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any">Promise.any()</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race()</a>.</p>
<p>Read the following tutorial to learn about promises in detail:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/">https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/</a></div>
<p> </p>
<h2 id="heading-how-to-use-the-async-and-await-keywords">How to Use the <code>async</code> and <code>await</code> Keywords</h2>
<p><code>await</code> keyword pauses execution of a function till a promise has been resolved or rejected. <code>await</code> can only be used inside an <code>async</code> function. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dataPromise</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Data retrieved"</span>), <span class="hljs-number">500</span>);
    });
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> dataPromise();
        <span class="hljs-built_in">console</span>.log(res); <span class="hljs-comment">// Data retrieved (after 500ms)</span>
    } <span class="hljs-keyword">catch</span>(err) {
        <span class="hljs-built_in">console</span>.log(err);
    }
}

fetchData();
</code></pre>
<p>When <code>dataPromise()</code> is called, the execution of the function pauses for 500ms. The execution continues after the promise has resolved. To handle errors, surround the code with a <code>try-catch</code> block.</p>
<p>The <code>await</code> keyword also makes it easier to work with multiple promises that run one after the other.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">promise1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Promise 1 resolved"</span>), <span class="hljs-number">500</span>);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">promise2</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Promise 2 resolved"</span>), <span class="hljs-number">300</span>);
    });
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res1 = <span class="hljs-keyword">await</span> promise1();
        <span class="hljs-built_in">console</span>.log(res1); <span class="hljs-comment">// Promise 1 resolved (after 500ms)</span>
        <span class="hljs-keyword">const</span> res2 = <span class="hljs-keyword">await</span> promise2();
        <span class="hljs-built_in">console</span>.log(res2); <span class="hljs-comment">// Promise 2 resolved (after 300ms)</span>
    } <span class="hljs-keyword">catch</span>(err) {
        <span class="hljs-built_in">console</span>.log(err);
    }
}

fetchData();
</code></pre>
<p><code>async</code> and <code>await</code> makes it easier to work with promises and also makes your code cleaner and readable by removing nesting in the code.</p>
<h2 id="heading-what-is-an-event-loop">What is an Event Loop?</h2>
<p>Event loop explains the mechanism behind asynchronous operations and event handling. This is a crucial concept in JavaScript that explains its runtime model and thus, one of the most commonly asked question in interviews.</p>
<p>Instead of providing a brief explanation, I think you should learn it in detail and understand it fully. Read the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop">MDN Docs</a> to understand event loop in detail, with the help of diagram.</p>
<p>If you prefer videos, you can also watch the following video by Philip Roberts:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8aGhZQkoFbQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-how-event-propagation-works-bubbling-and-capturing">How Event Propagation Works – Bubbling and Capturing</h2>
<p>Event propagation takes place when an event is captured and handled by the target element and all its ancestors. Take the following example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"box"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>When you click the button, you have also clicked the <code>div</code> element as well the <code>body</code>. The event is propagated throughout the DOM tree. Let's add handlers to all the above elements:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Body clicked"</span>);
});

<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"box"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"div clicked"</span>);
});

<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
});
</code></pre>
<p>Event propagation occurs in two ways:</p>
<h3 id="heading-event-bubbling">Event Bubbling</h3>
<p>When the button is clicked, the event handler of the button is called first. Then, the event bubbles up the DOM tree and the event handlers of parents are called sequentially from the immediate parent to the highest ancestor. That is: the <code>div</code> and <code>body</code> elements respectively.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-52.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Event Bubbling</em></p>
<h3 id="heading-event-capturing">‌Event Capturing</h3>
<p>This works similar to event bubbling, but in reverse. The event is first captured by the root element, then travels down the DOM tree to the target element.</p>
<p>The event handlers are called in sequence starting from the root element, down to the target element. This can be achieved by passing <code>true</code> as the third parameter in the <code>addEventListener()</code> function.‌</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Body clicked"</span>);
}, <span class="hljs-literal">true</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-53.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Event Capturing</em></p>
<p>However, this looks counter-productive. After all, the user only wants to click the button, they have no idea of the DOM tree structure. So, to prevent this behaviour, we can use the <code>stopPropagation()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.stopPropagation();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Stopped propagation</em></p>
<h2 id="heading-what-are-generator-functions">What are Generator Functions?</h2>
<p>Generator functions are special type of functions that can pause their execution and resume it later. They also return a value each time they pause execution.</p>
<p>Generator functions can be used to return a sequence of values in an iterative manner as opposed to normal functions that return only once.</p>
<p>Following is a basic example of a generator function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">generatorFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
}
</code></pre>
<p>A generator function is declared with <code>function*</code> and the <code>yield</code> keyword is used to pause execution and return a value. The above syntax creates a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction">GeneratorFunction</a> object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> gen = generatorFunction()
</code></pre>
<p>‌This object uses an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol">iterator</a> to execute a generator function. The iterator provides a <code>next()</code> method that executes the function's body till the next yield statement and returns an object containing the yielded value and a <code>done</code> property (Boolean), which indicates if the generator function has reached its end.</p>
<p>Let's call the generator function:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(gen.next().value); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 2, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: undefined, done: true }</span>
</code></pre>
<p>‌Here, the first call to <code>next()</code> yields 1 and the second one yields 2. The last one yields nothing and sets the <code>done</code> flag to true as there are no more <code>yield</code> statements.</p>
<p>You can also loop over a generator function using <code>for</code> loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(value <span class="hljs-keyword">of</span> generatorFunction()) {
  <span class="hljs-built_in">console</span>.log(value)
}
</code></pre>
<p>In this way, you can control the execution of a generator function by entering and exiting a function at any time.</p>
<h2 id="heading-how-to-implement-polyfills-for-arraymap-arrayreduce-and-arrayfilter">How to Implement Polyfills for <code>Array.map()</code>, <code>Array.reduce()</code>, and <code>Array.filter()</code></h2>
<p>JavaScript has evolved a lot since its inception. Several methods and constructs have been added to JavaScript that didn't exist before. Most modern browsers use the latest versions of JavaScript.</p>
<p>However, there are several applications still running on older browsers that use older versions of JavaScript . Array methods like <code>map</code>, <code>reduce</code> and <code>filter</code> may not be available. Therefore, you may have to provide polyfills for these methods.</p>
<p>Polyfills are pieces of code that provide modern functionality to older browsers that don't support it. This ensures that your code runs seemlessly on different browsers and versions.</p>
<p>Most companies have websites that still cater to users and systems running old browsers. So, knowing how to write polyfills for frequently used methods is important.</p>
<p>In our case, we are going to write polyfills for <code>Array.map</code>, <code>Array.reduce</code> and <code>Array.filter</code> methods. This means we are going to write our own implementations instead of using the default ones.</p>
<h3 id="heading-arraymap"><code>Array.map</code></h3>
<p>This method takes a callback function as a parameter, executes it on each array element and returns a new, modified array.</p>
<p>The callback function takes three arguments: the array element, index and the array itself. The last two arguments are optional.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.prototype.map = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">var</span> newArray = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    newArray.push(callback(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>));
  }
  <span class="hljs-keyword">return</span> newArray;
};
</code></pre>
<p>‌The logic is simple. Call the function for each element of the array and append each value to the new array. The <code>this</code> keyword is the object on which you are calling the function, in this case, the array.</p>
<h3 id="heading-arrayfilter"><code>Array.filter</code></h3>
<p>This method also takes a callback function as a parameter. The callback function runs a condition on each array element and returns a Boolean value. The <code>filter</code> method returns a new, filtered array containing elements that satisfy the condition.</p>
<p>This callback function takes three arguments: the array element, index and the array itself. The last two arguments are optional.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.prototype.filter = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">var</span> filteredArr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    <span class="hljs-keyword">var</span> condition = callback(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">if</span> (condition) {
      filteredArr.push(<span class="hljs-built_in">this</span>[i]);
    }
  }
  <span class="hljs-keyword">return</span> filteredArr;
};
</code></pre>
<p>Here, use the Boolean value returned by the callback function to add elements to the new array.</p>
<h3 id="heading-arrayreduce"><code>Array.reduce</code></h3>
<p>This method takes a callback function and an initial value as parameters and reduces the array to a single value. This is done by executing the function on the accumulator and current value and storing the result into the accumulator.</p>
<p>The callback function takes four arguments: the accumulator, current element, index and array itself. The last two arguments are optional.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.prototype.reduce = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback, initialValue</span>) </span>{
    <span class="hljs-keyword">var</span> accumulator = initialValue;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
        <span class="hljs-keyword">if</span> (accumulator !== <span class="hljs-literal">undefined</span>) {
            accumulator = callback(accumulator, <span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>);
        } <span class="hljs-keyword">else</span> {
            accumulator = <span class="hljs-built_in">this</span>[i];
        }
    }
    <span class="hljs-keyword">return</span> accumulator;
};
</code></pre>
<p>Initially, set the accumulator to the initial value. Execute the callback function for each array element and store the result in accumulator. If the accumulator is undefined, then set it to the element itself.</p>
<p>Let's test these methods:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-built_in">console</span>.log(arr.map(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele * <span class="hljs-number">2</span>)); <span class="hljs-comment">// [ 2, 4, 6 ]</span>
<span class="hljs-built_in">console</span>.log(arr.filter(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele &lt; <span class="hljs-number">2</span>)); <span class="hljs-comment">// [ 1 ]</span>
<span class="hljs-built_in">console</span>.log(arr.reduce(<span class="hljs-function">(<span class="hljs-params">total, ele</span>) =&gt;</span> total + ele, <span class="hljs-number">0</span>)); <span class="hljs-comment">// 6</span>
</code></pre>
<p><strong>Note:</strong> Before adding a polyfill for any property, always check if the property exists on the object's prototype, or you might override the existing behaviour. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.map)
</code></pre>
<h2 id="heading-additional-thoughts">Additional Thoughts</h2>
<p>Before we wrap up, I would like to share a few additional thoughts. Cracking a JavaScript interview isn't just about memorizing concepts. Make sure you dive deep into each topic and understand it thoroughly, including its applications.</p>
<p>Additionally, don't underestimate the importance of soft skills like communication. Conveying your thoughts clearly to the interviewer is as important as knowing your stuff.</p>
<p>When you're asked questions about any of the above concepts, start by briefly explaining the concept and then use an example for a more detailed explanation.</p>
<p>Explaining with examples is crucial for answering any interview question. It makes it easier for interviewers to understand your thought process. In this post, I've also followed a similar pattern while explaining each concept.</p>
<p>Lastly, keep revisiting this handbook throughout your interview preparation. Feel free to use it as a cheat sheet. If you are an experienced developer, this handbook will also help you revisit and reinforce these concepts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Interviews can be quite scary and unpredictable. While there is a high demand for JavaScript skills, the competition is equally intense. Building a strong foundation is crucial for successful interview preparation.</p>
<p>In this handbook, I have outlined several important topics to prepare for your next JavaScript interview and provided detailed explanations for each concept. While this is not an exhaustive list, it covers several critical concepts. If you think I've missed any important topics, please let me know.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, comment your thoughts below. New ideas are always appreciated! Feel free to connect with me on Twitter.</p>
<p>Good luck with your interviews !!!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement an OAuth2 Resource Server with Spring Security ]]>
                </title>
                <description>
                    <![CDATA[ Hey everyone! Imagine you are building an awesome application, with lots of cool features. Picture a backend server at its core that hosts a majority of the business logic and exposes functionality through APIs. Once you have planned out your APIs, t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/oauth2-resourceserver-with-spring-security/</link>
                <guid isPermaLink="false">66d8516039c4dccc43d4d4c3</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ spring-boot ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Wed, 08 May 2024 15:39:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/article-cover.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hey everyone! Imagine you are building an awesome application, with lots of cool features. Picture a backend server at its core that hosts a majority of the business logic and exposes functionality through APIs.</p>
<p>Once you have planned out your APIs, there's one crucial step you need to take care of: securing your APIs. You don't want your APIs exposed to anyone on the internet (unless you are building for open source).</p>
<p>Authentication ensures that your APIs can only be accessed by authenticated users of your application. A user can be authenticated with username and password, or via access token.</p>
<p>In this post, we are going to see how to secure your APIs using OAuth2 and access tokens. I am assuming you have a basic knowledge of Java and Spring Boot. If not, then you can <a target="_blank" href="https://www.freecodecamp.org/news/learn-app-development-with-spring-boot-3/">check out this course on freeCodeCamp's YouTube channel</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-oauth2">What is OAuth2?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-the-spring-boot-application">How to Set Up the Spring Boot Application</a></p>
</li>
<li><p><a class="post-section-overview" href="#configuration">Web Security Configuration</a></p>
</li>
<li><p><a class="post-section-overview" href="#write-apis-in-controller-class">Public and Private APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-testing-the-apis">Testing APIs with and without Access Token</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-the-users-details-from-the-access-token">How to Get the User's Details From the Access Token</a></p>
</li>
</ol>
<h2 id="heading-what-is-oauth2">What is OAuth2?</h2>
<p>OAuth2 is a framework that lets third-party applications access your service on behalf of an end user. It is widely used for authentication and authorization in modern applications.</p>
<p>There are four components in the OAuth2 framework:</p>
<ul>
<li><p><strong>Resource Owner</strong>: The end-user of your application.</p>
</li>
<li><p><strong>Authorization Server</strong>: The third-party application that authenticates the user and issues an access token after successful authentication.</p>
</li>
<li><p><strong>Client</strong>: The user interface through which the user wants to access your resources. The client could be a mobile app, web app, or a desktop app. The client requires an access token to access your APIs.</p>
</li>
<li><p><strong>Resource Server</strong>: The server hosting the protected resources. It validates the access token and grants access to the resources if authentication is successful.</p>
</li>
</ul>
<p>The user, through the client, requests an access token from the authorization server. If authentication is successful, the client uses this token to access the protected APIs exposed by the resource server.</p>
<p>In this post, we are only going to focus on implementing the resource server.</p>
<h2 id="heading-how-to-set-up-the-spring-boot-application">How to Set Up the Spring Boot Application</h2>
<p>To set up your application, navigate to <a target="_blank" href="https://start.spring.io/">Spring Initializr</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Spring Initializr</em></p>
<p>Choose <em>Gradle</em> or <em>Maven</em> for the project, the Spring Boot version, and the name of the project. Add the following dependencies: <em>spring-boot-starter-web</em> and <em>oauth2-resource-server</em>.</p>
<p>Click on <em>Generate</em> to download the Spring Boot application and once downloaded, extract the zip file. You should now have a running Spring Boot application with the dependencies fully loaded. Open IntelliJ (or any IDE of your choice) and select this project to start working.</p>
<p>You can find the complete code for this tutorial on <a target="_blank" href="https://github.com/KunalN25/my-tutorials/tree/main/java-springboot/oauth2-resource-server-tutorial">GitHub</a>.</p>
<h2 id="heading-web-security-configuration">Web Security Configuration</h2>
<p>First, open <code>application.properties</code> and add the following property:</p>
<pre><code class="lang-python">spring.security.oauth2.resourceserver.jwt.issuer-uri: ${JWT_ISSUER_URI}
</code></pre>
<p>You can find the <em>issuer-uri</em> in the open-id configuration of the OAuth2 service that you are using. For instance, check out the <a target="_blank" href="https://accounts.google.com/.well-known/openid-configuration">Google OAuth2</a> config.</p>
<p>Next, let's configure Spring Security.</p>
<p>To implement the resource server, you need to have Spring Security as one of your dependencies. Here, we don't need to add it separately since the <em>oauth2-resource-server</em> uses Spring Security.</p>
<p>When you add Spring Security in your dependencies, Spring Boot enables authentication for each API you expose. The default one is username and password-based authentication.</p>
<p>This happens because Spring Security has its own <code>SecurityAutoConfiguration</code> class that contains the default security configuration. But, we haven't added Spring Security in our dependencies.</p>
<p>Since we do not want username and password-based authentication, we need to disable the auto configuration. Go to the main class and add the following exclusion:</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootApplication(exclude = { SecurityAutoConfiguration.class})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Oauth2ResourceServerTutorialApplication</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(Oauth2ResourceServerTutorialApplication.class, args);
    }
}
</code></pre>
<p>If you run the application now, it throws an error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-45.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Error without configuration</em></p>
<p>Let's add our own configuration now. Create a new Java class <code>SecurityConfig</code> with the following annotations:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> </span>{
    <span class="hljs-comment">// Beans here</span>
}
</code></pre>
<p><code>@Configuration</code> indicates that this is a configuration class that contains several Bean methods, that are responsible for creating beans. <a target="_blank" href="https://www.baeldung.com/spring-bean">Beans</a> are simply objects that form the building blocks of a Spring Boot application. <code>@EnableWebSecurity</code> tells Spring Boot to enable Web Security with your configurations.</p>
<p>Create a method that returns a bean of type <code>SecurityFilterChain</code>. The security filter chain bean intercepts incoming requests and applies custom filters to them. This is where you can apply different kinds of authorization to different requests.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> SecurityFilterChain <span class="hljs-title">filterChain</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        http
                .authorizeHttpRequests((authz) -&gt; authz
                        .requestMatchers(<span class="hljs-string">"/public/**"</span>).permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));
        <span class="hljs-keyword">return</span> http.build();
    }
</code></pre>
<p>Let's understand the key parts of this code:</p>
<ul>
<li><p>The <code>filterChain()</code> method takes an <code>HttpSecurity</code> object as an argument. This class from Spring Security allows you to configure requests.</p>
</li>
<li><p>The method <code>authorizeHttpRequests()</code> takes an object that we have represented as a lambda expression.</p>
</li>
<li><p>We have used the <code>requestMatchers()</code> method to match a route that will be accessible without authentication. In our case, any route starting from <code>/public</code> will be accessible to anyone. Requests to any other route will need authentication.</p>
</li>
<li><p>The <code>oauth2ResourceServer()</code> method sets up our application as an OAuth2 resource server. Here, we specify that JWT authentication will be used with default customizers.</p>
</li>
<li><p>Lastly, <code>http.build()</code> builds the <code>HttpSecurity</code> object and returns it.</p>
</li>
</ul>
<p>In this project, we have configured web security in the above manner. But if you have any other requirements you may need a different configuration. For example, if you have privileged roles like admin in your application, you can specify which routes each role can access, and so on.</p>
<p>Visit the <a target="_blank" href="https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html">JWT resource server</a> docs to understand different ways you can customize web security.</p>
<h2 id="heading-write-apis-in-the-controller-class">Write APIs in the Controller Class</h2>
<p>Let's write two simple APIs. Create a class <code>MainController</code> that will expose these APIs:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainController</span> </span>{

    <span class="hljs-meta">@GetMapping("/public")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">homePage</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from Spring boot app"</span>;
    }

    <span class="hljs-meta">@GetMapping("/private")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">privateRoute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Private Route"</span>;
    }
}
</code></pre>
<p>The <code>@RestController</code> indicates that this class will handle HTTP requests and return the data to the client, typically in JSON format. We have written a public and a private API.</p>
<p>Save the file and run the application.</p>
<h2 id="heading-testing-the-apis">Testing the APIs</h2>
<p>Let's test the above APIs using Postman, without an authorization header.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>/public route</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>/private route</em></p>
<p>In the above two API calls, the <code>/public</code> route returned a response, while the <code>/private</code> route threw an error with a status of <code>401 Unauthorized</code>.</p>
<p>This is because, in our configuration, we have made all routes starting with <code>/public</code> accessible without authentication. All the other routes would need some form of authentication. In our case, we need a Bearer Token to access the private route.</p>
<p>Let's include an authorization header in the request to the <code>/private</code> endpoint.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>/private route request with access token</em></p>
<p>When we include an authorization header with the access token, the private route returns a response. For this, and any other routes not starting with <code>/public</code>, we need to pass an access token in the header.</p>
<p>We are not going to see how to obtain an access token, since we are only focussing on the resource server. The OAuth2 Client is responsible for obtaining an access token. I'll cover that in a future post.</p>
<h2 id="heading-how-to-get-the-users-details-from-the-access-token">How to Get the User's Details From the Access Token</h2>
<p>When you make a request to a private route, the security filter intercepts this request and looks for a Bearer Token. If a token exists, it decodes the token and extracts the authentication information from the token. You can understand this whole process in detail from the <a target="_blank" href="https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/index.html">OAuth2 Resource Server</a> docs.</p>
<p>If the token is valid and authentication is successful, the authentication data is set on the <a target="_blank" href="https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html#servlet-authentication-securitycontextholder">SecurityContextHolder</a> class. The <code>SecurityContextHolder</code> contains the details of the authenticated user. We use this class to extract the user's information such as name, email, and so on.</p>
<p>Let's see how we can get these user details. First, we get an <a target="_blank" href="https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html#servlet-authentication-authentication">Authentication</a> object from the <code>SecurityContextHolder</code>:</p>
<pre><code class="lang-java">Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
</code></pre>
<p>Then, we use the <code>getPrincipal()</code> that returns an object:</p>
<pre><code class="lang-java">Object principal = authentication.getPrincipal();
</code></pre>
<p>Since we are using JWT Authentication, the above object can be type-casted into an object of type <a target="_blank" href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/oauth2/jwt/Jwt.html">Jwt</a>. The object contains the following fields:</p>
<pre><code class="lang-python">{
    <span class="hljs-string">"tokenValue"</span>: token_value,
    <span class="hljs-string">"issuedAt"</span>: <span class="hljs-string">""</span>,
    <span class="hljs-string">"expiresAt"</span>: <span class="hljs-string">""</span>,
    <span class="hljs-string">"headers"</span>: {...},
    <span class="hljs-string">"claims"</span>: {        
        <span class="hljs-string">"name"</span>: full_name,
        <span class="hljs-string">"email"</span>: user_email,
        <span class="hljs-string">"given_name"</span>: first_name,
        <span class="hljs-string">"family_name"</span>: last_name,
        <span class="hljs-string">"picture"</span>: picture_link,
        ...other fields
    },
    <span class="hljs-string">"subject"</span>: <span class="hljs-string">""</span>,
    <span class="hljs-string">"id"</span>: null,
    <span class="hljs-string">"issuer"</span>: issuer_link,
    <span class="hljs-string">"audience"</span>: [...],
    <span class="hljs-string">"notBefore"</span>: null
}
</code></pre>
<p>Here, we can get the user data from the <code>claims</code> field:</p>
<pre><code class="lang-java">Map&lt;String, Object&gt; claims = ((Jwt) principal).getClaims();
</code></pre>
<p>Using the above map, we can get the user's information using the corresponding key value. Let's write this logic in a separate class <code>CurrentAuthContext</code>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CurrentAuthContext</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Map&lt;String, Object&gt; <span class="hljs-title">extractClaim</span><span class="hljs-params">()</span> </span>{
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        Map&lt;String, Object&gt; claims = ((Jwt) principal).getClaims();
        <span class="hljs-keyword">return</span> claims;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getUserEmail</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> (String) extractClaim().get(<span class="hljs-string">"email"</span>);
    }
}
</code></pre>
<p>You can add more methods to get the details you need. To get the user email anywhere in the application, just call <code>CurrentAuthContext.getUserEmail()</code> or any other method returning the value you need.</p>
<p>I haven't implemented custom error handling here. You can reach out to me with different ways to implement custom error handling.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>OAuth2 provides a robust framework for securing your APIs while providing access to authorized users. In this post, we started with understanding OAuth2 and its components.</p>
<p>Spring Security is a fundamental part of the Spring OAuth2 Resource Server. We learned how to implement security configurations as per our requirements. Then, we defined public and private APIs and tested them with and without an access token.</p>
<p>A private API can only be accessed with an access token passed through the authorization header. We also implemented some logic to extract the user's information from the access token with the <code>SecurityContextHolder</code> class.</p>
<p>I attached reference links to docs at various places for further understanding of these concepts. That's all for today. I hope this helps in your future projects.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, reach out to me. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, Goodbye!!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Throttling in JavaScript? Explained with a Simple React Use Case ]]>
                </title>
                <description>
                    <![CDATA[ Welcome back, fellow developers! Today, we are once again delving into JavaScript and Web Development and learning about throttling. As a developer, making your website user-friendly is important. This goes a long way toward the product's success, an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/throttling-in-javascript/</link>
                <guid isPermaLink="false">66d85164057dcda12008e29d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Wed, 01 May 2024 15:58:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/throttling-image.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome back, fellow developers! Today, we are once again delving into JavaScript and Web Development and learning about throttling.</p>
<p>As a developer, making your website user-friendly is important. This goes a long way toward the product's success, and a key part of the user experience is the website's performance.</p>
<p>In a <a target="_blank" href="https://www.freecodecamp.org/news/deboucing-in-react-autocomplete-example/">previous tutorial</a>, I discussed how to improve the performance of any feature using a technique called debouncing. And you can use a similar technique, called throttling, but in a slightly different scenario. You'll learn how to implement throttling in this article.</p>
<p>For this guide, I am assuming you have a basic knowledge of JavaScript. Don't worry if you are a beginner – I have provided simple and detailed explanations to guide you through. So, let's dive right into it!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-throttling">What is Throttling?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-throttling-in-javascript">How to Implement Throttling in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-whats-a-closure-in-javascript">What is a Closure in JavaScript</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-case-of-function-throttling">Use Case of Function Throttling</a></p>
</li>
</ol>
<h2 id="heading-what-is-throttling">What is Throttling?</h2>
<p>Throttling is a technique used to limit the rate at which a function is called. Throttling transforms a function such that it can only be called once in a specific interval of time.</p>
<p>Let's understand this with an example. Let's take a function <code>fun()</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a function'</span>)
}
</code></pre>
<p>We want to modify this function so that it can only be called once in 500ms. So, throttling will take <code>fun()</code> as an input, and return a modified (throttled) function <code>throttledFun()</code> that can only be executed 500ms after the previous function was executed.</p>
<p>When you call <code>throttledFun()</code> multiple times within 500ms, <code>fun()</code> will only be executed the first time. You will have to wait 500ms before <code>fun()</code> can be executed again. This happens after every subsequent function call. Thus, <code>fun()</code> can only be called once every 500ms.</p>
<h2 id="heading-how-to-implement-throttling-in-javascript">How to Implement Throttling in JavaScript</h2>
<p>Let's first understand what we want to achieve with throttling:</p>
<ul>
<li><p>Call the function immediately the first time.</p>
</li>
<li><p>After each call, prevent the function from being called again for a certain time period.</p>
</li>
<li><p>Once that time period has passed, the function can be called again.</p>
</li>
</ul>
<p>To do all this, let's first create a helper function that will return a throttled function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
      <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {}   <span class="hljs-comment">// return throttled function</span>
}
</code></pre>
<p>For any use cases, the throttled function will be used instead of the original <code>fun()</code>.</p>
<p>Let's start by simply calling the function like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        func()
    }
}
</code></pre>
<p>Once the function is called, we want to block it from being called again for a certain time period <code>delay</code>. Once the time has passed, we want to unblock the function. We can achieve this behaviour using <code>setTimeout</code>.</p>
<p>For now, let's keep the <code>setTimeout</code> empty. You'll understand how it works in a minute.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {}, delay)
</code></pre>
<p>Next, we'll declare a variable <code>timeout</code> that will be initialized only once in the outer function (that is the <code>throttle()</code> function). The <code>setTimeout</code> method returns a unique timeout id that we can use to identify a timeout. We'll assign the current timeout id to <code>timeout</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
    <span class="hljs-keyword">let</span> timeout=<span class="hljs-literal">null</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        func()
        timeout=<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-comment">// do something</span>
        }, delay)
    }
}
</code></pre>
<p>Since <code>timeout</code> contains the id of the current timeout, we add a condition at the start of the throttled function to check if a timeout exists before calling the original function <code>func()</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
    <span class="hljs-keyword">let</span> timeout=<span class="hljs-literal">null</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span>(!timeout) {
            func()
            timeout=<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
                <span class="hljs-comment">// do something</span>
            }, delay)
        }
    }
}
</code></pre>
<p>Initially, <code>timeout</code> is null, so the function is executed. The throttled function then starts a new timeout and assigns it to the <code>timeout</code> variable. In the next function call, it checks if a timeout exists before calling <code>func()</code>. If a timeout already exists, it does not execute <code>func()</code>.</p>
<p>But what happens after the time period of <code>delay</code> has passed? Inside the <code>setTimeout</code> we need to do something that enables <code>func()</code> to be called again. Since we are using <code>timeout</code> to control the function calls, we set it to null after <code>delay</code> milliseconds.</p>
<pre><code class="lang-javascript">timeout=<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    timeout=<span class="hljs-literal">null</span>
}, delay)
</code></pre>
<p>Now, when you call the function, it is executed and the process repeats by starting a new timeout. We have successfully throttled the function.</p>
<p>But there's something fundamental that we are still overlooking. In the current function call, once we assign <code>setTimeout</code> to the <code>timeout</code> variable, for the next one we are assuming that <code>timeout</code> is still valid and holds the value that we want – even if the variable is declared inside the <code>throttle()</code> function.</p>
<p>How is the inner function still able to have access to the variable long after the <code>throttle()</code> function has finished execution? It uses a concept called a closure. Let's take a quick detour to visit this concept.</p>
<h3 id="heading-whats-a-closure-in-javascript">What's a closure in JavaScript?</h3>
<p>In JavaScript, an inner function always has access to the local variables of the outer function. In our case, the inner function has access to <code>timeout</code> that has function level scope in the <code>throttle()</code> method.</p>
<p>But when the outer function returns this inner function, the inner function still holds a reference to the local variables of the outer function long after the outer function has finished execution. This is the concept of a closure.</p>
<p>Let's understand closures with an example.</p>
<pre><code class="lang-python">function outerFunction() {
  const x = <span class="hljs-number">5</span>;

  <span class="hljs-keyword">return</span> () =&gt; {
    console.log(x);
  }
}

const inner = outerFunction();

inner(); // prints <span class="hljs-number">5</span>

// console.log(x)   Throws reference error
</code></pre>
<p>Here, if we call <code>inner()</code>, the code runs without any errors and prints 5. But, if we try to access <code>x</code> directly, JavaScript throws a reference error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-141749.png" alt="Screenshot-2024-02-09-141749" width="600" height="400" loading="lazy"></p>
<p><em>JavaScript Reference Error: "x is not defined"</em></p>
<p>Here, <code>inner()</code> closes over <code>x</code> and only this function can use the variable and no one other one can. We cannot access the variable explicitly.</p>
<p>You can check out <a target="_blank" href="https://www.freecodecamp.org/news/closures-in-javascript/">this beginner-friendly tutorial</a> to learn more about closures.</p>
<h3 id="heading-back-to-throttling">Back to throttling</h3>
<p>Let's continue from where we left off.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, delay</span>) </span>{
    <span class="hljs-keyword">let</span> timeout=<span class="hljs-literal">null</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span>(!timeout) {
            func()
            timeout=<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
                timeout=<span class="hljs-literal">null</span>
            }, delay)
        }
    }
}
</code></pre>
<p>We have seen that JavaScript uses closures to hold access to <code>timeout</code> every time we call the throttled function.</p>
<p>With this, we have a basic implementation of function throttling.</p>
<p>Let's test it out by using the above <code>fun()</code> method and throttling it with a delay of 500ms. This function should only be able to execute once every 500ms.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> throttledFun = throttle(fun, <span class="hljs-number">500</span>)
</code></pre>
<p>Let's call <code>throttledFun()</code> in different ways and see how it executes.</p>
<pre><code class="lang-javascript">throttledFun(); <span class="hljs-comment">// This will execute immediately</span>
throttledFun(); <span class="hljs-comment">// This will be ignored</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  throttledFun(); <span class="hljs-comment">// This will also be ignored</span>
}, <span class="hljs-number">300</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  throttledFun(); <span class="hljs-comment">// This will execute</span>
}, <span class="hljs-number">600</span>);
</code></pre>
<p>The first function call will execute immediately. For the next 500ms (throttling delay in this example), no matter how many times you call <code>throttledFun()</code>, nothing will happen.</p>
<p>So, the second function call and the third one won't execute, because they occur within 500ms of the first call. Once 500ms have passed, the next function call – that is, the last one – will execute, since the call is being made after 500ms.</p>
<p>Thus, it will print the following output:</p>
<pre><code class="lang-console">This is a function
This is a function // Printed after 600ms
</code></pre>
<p>The solution is not complete yet. Our approach does not take into account function arguments. So, let's modify <code>fun()</code> to have two arguments:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params">a,b</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is a function with args <span class="hljs-subst">${a}</span> and <span class="hljs-subst">${b}</span>`</span>)
}
</code></pre>
<p>To incorporate arguments, use the spread operator <code>...</code> and store all arguments in a variable <code>args</code>:</p>
<pre><code class="lang-python">function throttle(func, delay) {
    let timeout=null
    <span class="hljs-keyword">return</span> (...args) =&gt; {
        <span class="hljs-keyword">if</span>(!timeout) {
            func(...args)
            timeout=setTimeout(() =&gt; {
                timeout=null
            }, delay)
        }
    }
}
</code></pre>
<p>Now, call <code>throttledFun()</code> again, with arguments like this:</p>
<pre><code class="lang-javascript">throttledFun(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>);
</code></pre>
<p>This will print <code>This is a function with args 2 and 3</code>.</p>
<h2 id="heading-use-case-of-function-throttling">Use Case of Function Throttling</h2>
<p>Let's see how throttling is used in practical applications. We'll take a button that makes a call to the backend server when a user clicks it. An API call is made every time someone clicks the button.</p>
<p>But an API request can take some time, and if the user clicks the button again, or repeatedly in a short time, more and more API calls are made which could overload the server. To avoid this behaviour, we use function throttling. Let's implement this with React.</p>
<h3 id="heading-set-up-the-project">Set Up the Project</h3>
<p>Run <code>create-react-app</code> in your terminal or use a <a target="_blank" href="https://www.freecodecamp.org/news/get-started-with-vite/">modern built tool like Vite</a> to create your React app. Remove the existing boilerplate code. There is no need to install any additional dependencies. Run <code>npm start</code> command to start the project. You can find the complete code on <a target="_blank" href="https://github.com/KunalN25/react-throttling">GitHub</a>.</p>
<p>I have set up a Node server to fetch data for the app. You can find it in the Git repo. Run the <code>node server</code> command to start it. I am not going to show the Node.js code as it's out of the scope of this tutorial.</p>
<p>Let's start with the implementation.</p>
<h3 id="heading-app-component">App Component</h3>
<p>In the App component, let's create a button with an <code>onClick</code> handler that makes an API call to the Node server.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"http://localhost:8000/data"</span>);
    <span class="hljs-keyword">return</span> resp.json();
  };
  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    fetchData().then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(data);
    });
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Now, let's click this button repeatedly.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-27.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multiple API Calls</em></p>
<p>Here, an API call is made every time the button is clicked. So, if the user clicks on the button repeatedly, a lot of API calls will be made in one second. This may overload the server.</p>
<p>To tackle this, we need to prevent the API from getting called on every click of the button. Let's see how to achieve this with throttling.</p>
<h3 id="heading-implement-throttling-using-a-custom-hook">Implement Throttling using a Custom Hook</h3>
<p>We'll write the throttling logic inside a custom hook. Since you may need throttling in multiple places in your application, it is recommended to put the logic inside a custom hook.</p>
<p>Create a new folder called <code>custom-hooks</code>. Inside it, create a file <code>useThrottle.js</code>. Inside the file, create and export new function <code>useThrottle()</code>. The method should take a function and delay as parameters and return the throttled function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> useThrottle = <span class="hljs-function">(<span class="hljs-params">func, delay</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> timeout = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (timeout) {
      <span class="hljs-keyword">return</span>;
    }
    func(...args);
    timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      timeout = <span class="hljs-literal">null</span>;
    }, delay);
  };
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useThrottle;
</code></pre>
<p>Now, inside the App component, call this method and pass the click handler <code>handleClick()</code> and a delay of 1000ms.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> handleClickThrottled = useThrottle(handleClick, <span class="hljs-number">1000</span>);
</code></pre>
<p>We'll use this function as the event handler for our button.</p>
<pre><code class="lang-javascript">&lt;button onClick={handleClickThrottled}&gt;Click Me&lt;/button&gt;
</code></pre>
<h3 id="heading-output">Output</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API Calls after Throttling</em></p>
<p>After clicking the button repeatedly for two seconds, only two API calls are made.</p>
<p>By limiting the number of times your APIs are called, throttling improves the performance of your application.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned what throttling is and how to implement it. Throttling allows you to control the rate at which a function can be executed in a specific period.</p>
<p>Throttling uses an important concept called closures. They allow you to work with local variables even after a function has finished execution. Closures can be quite confusing for beginners, so take your time with them.</p>
<p>After that, I showed you a common use case of throttling, where you can control how many times an API call can be made on multiple button clicks. I utilized custom hooks to implement throttling in React. This serves to improve the performance of web applications. I hope this helps you in your future projects.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Solve the Producer-Consumer Problem in Java using Multithreading ]]>
                </title>
                <description>
                    <![CDATA[ Concurrency is an important part of Java applications. Each application has multiple processes running at the same time. This helps utilize resources efficiently and improve performance. Multithreading is a method of achieving concurrency. It uses th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-multithreading-producer-consumer-problem/</link>
                <guid isPermaLink="false">66d85157f01807d1f69107db</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 04 Mar 2024 17:48:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/producer-consumer-problem-image.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Concurrency is an important part of Java applications. Each application has multiple processes running at the same time. This helps utilize resources efficiently and improve performance.</p>
<p>Multithreading is a method of achieving concurrency. It uses the concept of threads – lightweight processes – to execute multiple tasks in parallel. A very popular application of multithreading is the producer-consumer problem.</p>
<p>In this tutorial, we are going to understand what the producer-consumer problem is and touch upon threads and multithreading briefly. Then, we are going to understand how to solve the producer-consumer problem in Java using threads.</p>
<p>Now, I assume you have a basic knowledge of Java. If not, then check out the following resources.</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-java-free-java-courses-for-beginners/">Free Java Courses for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-java-programming/">Basics of Java Programming</a></p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-the-producer-consumer-problem">What is the Producer-Consumer Problem?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solution-using-producer-and-consumer-threads">Solution using Producer and Consumer Threads and Issue with Synchronization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-introducing-synchronization-in-the-message-queue">Introducing Synchronization in the Message Queue Class</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-producer-with-multiple-consumers">Producer with Multiple Consumers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solution-using-java-concurrencys-blockingqueue-class">Solution using Java Concurrency's BlockingQueue Class</a></p>
</li>
</ul>
<h2 id="heading-what-is-the-producer-consumer-problem">What is the Producer-Consumer Problem?</h2>
<p>The producer-consumer problem is a synchronization problem between different processes. There are three entities in this problem: a producer, a consumer, and a memory buffer. Both the producer and consumer share the same memory buffer.</p>
<p>The producer produces some items and pushes them into the memory buffer. A consumer then consumes these items by popping them out of the buffer. If the buffer is empty, then the consumer waits for the producer to push an item, which it consumes after the producer pushes it.</p>
<p>The memory buffer is of fixed size. If it is full, the producer waits for the consumer to consume an item before pushing a new one. The producer and consumer cannot access the buffer at the same time – that is, it's mutually exclusive. Each process should wait for the other to finish its work on the buffer before it can access the buffer.</p>
<p>Operating systems often encounter this problem where multiple processes access the same memory space to perform their tasks.</p>
<p>We will solve this problem using multithreading, so I assume you have a basic idea about what multithreading is and how it works. If not, then you can <a target="_blank" href="https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/">read through this tutorial</a>.</p>
<p>We'll start with an attempt to solve it simply using threads and a separate class for message queue. Then, we'll understand its issues and how to overcome them in the next approach. We'll also see other approaches to the problem. Make sure to stick around until the end.</p>
<h2 id="heading-solution-using-producer-and-consumer-threads">Solution using Producer and Consumer Threads</h2>
<p>Let's go over our requirements first.</p>
<ul>
<li><p>Producer and Consumer tasks run in separate threads</p>
</li>
<li><p>Common data bus, typically a message queue, used by both producer and consumer.</p>
</li>
<li><p>If not full, producer pushes data into queue, or waits for it to be consumed</p>
</li>
<li><p>If not empty, consumer takes data out of the queue, or waits for producer to publish.</p>
</li>
</ul>
<p>These are the things we need to implement to solve this problem. Let's create the message queue first.</p>
<h3 id="heading-message-queue">Message Queue</h3>
<p>To set up a message queue, we'll use a class that contains the queue and methods to publish and consume messages.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Data</span> </span>{ 
    Queue&lt;String&gt; q; 
    <span class="hljs-keyword">int</span> capacity; 

    Data(<span class="hljs-keyword">int</span> cap) { 
        q = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;(); 
        capacity=cap; 
    } 
    <span class="hljs-comment">// other methods </span>
}
</code></pre>
<p>Here, we have used Java's <code>Queue</code> class to store our messages. Each message is of type <code>String</code>. But in bigger applications, the message or payload could be of any object type. We also define the capacity of the message queue.</p>
<p>Next, we'll implement the <code>publish()</code> method. The method accepts a new message to be published.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> </span>{ <span class="hljs-comment">// publish message to the queue }</span>
</code></pre>
<p>First, we check if the queue is full. We can't publish a new message if the queue has reached capacity.</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size() == capacity){ 
    <span class="hljs-keyword">return</span>; 
}
</code></pre>
<p>If the queue is not full, then add the message to the queue.</p>
<pre><code class="lang-java">q.add(msg);
</code></pre>
<p>We'll add print statements to understand the workflow better.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size() == capacity){ 
        System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>); 
        <span class="hljs-keyword">return</span>; 
    } 
    q.add(msg); 
    System.out.println(<span class="hljs-string">"Message published:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
}
</code></pre>
<p>Here, we just print the thread that is inside the method, the message published, and the resulting queue.</p>
<p>Let's implement the <code>consume()</code> method now. This method does not take any arguments and works similarly to the <code>publish()</code> method. We first check if the queue is empty, before removing anything from the queue.</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
    <span class="hljs-keyword">return</span>; 
}
</code></pre>
<p>Then, we remove the message.</p>
<pre><code class="lang-java">q.poll();
</code></pre>
<p>Again, we'll add print statements to understand the workflow better.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span>  </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
        System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>); 
        <span class="hljs-keyword">return</span>; 
    } 
    String msg = q.poll(); 
    System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
}
</code></pre>
<h3 id="heading-producer-thread">Producer Thread</h3>
<p>Let's write the producer logic now. We'll create a class <code>Producer</code> that will run in a thread. There are <a target="_blank" href="https://www.javatpoint.com/how-to-create-a-thread-in-java">several ways to create threads</a> in Java. We'll use the <code>Runnable</code> interface to create our thread since it's the most preferred approach.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Producer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{ 
    Data data; 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Producer</span><span class="hljs-params">(Data data)</span> </span>{ 
        <span class="hljs-keyword">this</span>.data = data; 
    } 

    <span class="hljs-meta">@Override</span> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{ } 
}
</code></pre>
<p>The producer has access to the data bus object which is passed to it via the constructor. The producer logic goes inside the <code>run()</code> method. By overriding the run method, you are writing functionality that runs in a thread.</p>
<p>Now, a producer's ways of producing and publishing data differs in every application. For this post, we are going to simulate a functionality where the producer keeps publishing messages every few seconds.</p>
<p>We'll define a list of messages that the producer can use.</p>
<pre><code class="lang-java"><span class="hljs-keyword">final</span> String[] messages={<span class="hljs-string">"Hi!!"</span>, <span class="hljs-string">"How are you!!"</span>, <span class="hljs-string">"I love you!"</span>, <span class="hljs-string">"What's going on?!!"</span>, <span class="hljs-string">"That's really funny!!"</span>};
</code></pre>
<p>Here's the producer logic inside the <code>run()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{ 
    <span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>; 
    <span class="hljs-keyword">try</span> { 
        <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){ 
            Thread.sleep(<span class="hljs-number">1000</span>); 
            data.publish(messages[i]); 
            i=(i+<span class="hljs-number">1</span>)%messages.length; 
        } 
    } <span class="hljs-keyword">catch</span> (InterruptedException e) {} 
}
</code></pre>
<p>In this code, the producer is publishing a message from the messages list every 1000 ms. <code>Thread.sleep(_some_delay_)</code> pauses execution of the thread for a certain period. Since it throws an exception, we surround the code with a try-catch block.</p>
<p>This is just for demonstration purposes – don't worry about the logic. Our implementation works regardless of the producer or consumer logic.</p>
<h3 id="heading-consumer-thread">Consumer Thread</h3>
<p>Similar to producer thread, let's simulate the consumer logic.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Consumer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{ 
    Data data; 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(Data data)</span> </span>{ 
        <span class="hljs-keyword">this</span>.data = data; 
    } 
    <span class="hljs-meta">@Override</span> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{ 
        <span class="hljs-keyword">try</span> { 
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){ 
                Thread.sleep(<span class="hljs-number">2000</span>); 
                data.consume(); 
            } 
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {} 
    } 
}
</code></pre>
<p>Here, the consumer tries to consume a message every 2000 ms.</p>
<h3 id="heading-putting-it-all-together">Putting it all Together</h3>
<p>Now, we have our message queue along with the producer and consumer classes. Let's create one producer and one consumer thread and start them.</p>
<p>We'll create a <code>Data</code> object with capacity of 5 messages and create our producer and consumer threads with the objects of the <code>Producer</code> and <code>Consumer</code> classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{ 
        Data data = <span class="hljs-keyword">new</span> Data(<span class="hljs-number">5</span>); 
        Thread producer=<span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Producer(data), <span class="hljs-string">"producer"</span>); 
        Thread consumer=<span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Consumer(data), <span class="hljs-string">"consumer"</span>);
        producer.start(); 
        consumer.start(); 
    } 
}
</code></pre>
<p>The <code>run()</code> method executes in a separate thread when <code>start()</code> is called.</p>
<h3 id="heading-output">Output:</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-23-211626-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Inconsistent output</em></p>
<p>Here, the output is inconsistent with the desired workflow. Even after publishing the first message, the consumer is still waiting. Then, a consumer has consumed a message <code>Hi!!</code> that doesn't exist. The state of the queue is also inconsistent.</p>
<p>You will probably get a different output, since thread execution depends on the core OS. But the issue still persists. Why does this happen?</p>
<h3 id="heading-synchronization-issue-with-the-data-class">Synchronization Issue With the Data Class</h3>
<p>Both producer and consumer threads run simultaneously, working on the same resource. They are accessing the message queue at the exact same time. Both the threads may start with one version of the resource and by the time they perform an operation, they are working on a different version.</p>
<p>This leads to a <a target="_blank" href="https://www.javatpoint.com/race-condition-in-operating-system">race</a> condition. Both threads end up competing for the same resource and give inconsistent results. The producer thread is trying to add a message to the queue, while at the same time a consumer is trying to consume a message. There's no way of controlling which message the consumer could get.</p>
<p>To solve this issue, we need some kind of mechanism to ensure that only one thread can operate on a shared resource at a time. In this case, we'll use the concept of <a target="_blank" href="https://www.geeksforgeeks.org/synchronization-in-java/">synchronization</a>.</p>
<p>At a glance, a synchronized function or a block can only be executed by one thread at a time. A thread entering such a block acquires a "lock" on the object and any other threads have to wait until the thread releases this lock – that is, until it finishes working on the shared resource.</p>
<p>We'll use a similar method to solve our issue.</p>
<h2 id="heading-introducing-synchronization-in-the-message-queue">Introducing Synchronization in the Message Queue</h2>
<p>To ensure the message queue is only accessed by one thread (producer or consumer) at a time, a thread needs to secure a lock on the <code>Data</code> object before performing any operations.</p>
<h3 id="heading-how-to-use-the-synchronized-keyword">How to Use the <code>synchronized</code> Keyword</h3>
<p>An object can be made mutually exclusive by using the synchronized keyword. We'll use the <code>synchronized</code> keyword with the <code>publish()</code> and <code>consume()</code> methods.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span></span>
</code></pre>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span></span>
</code></pre>
<p>Now, a thread needs to acquire a lock on the object before entering these methods.</p>
<h3 id="heading-what-are-the-wait-and-notify-methods">What are the <code>wait()</code> and <code>notify()</code> Methods?</h3>
<p>We have achieved synchronization – only one thread can access a shared resource at a time to ensure consistency. Now, we need to establish communication between the producer and consumer threads.</p>
<p>Let's understand what we need first. If the queue is full, the producer needs to wait for a consumer to consume an item. Similarly, if the queue is empty, the consumer needs to wait until the producer pushes an item.</p>
<p>Also, when a producer pushes an item, it needs to notify all the waiting consumer threads about the action. The is also true when the consumer consumes an item. So, how do we establish this communication?</p>
<p>We can do this using the <code>wait()</code> and <code>notify()</code> methods. When the <code>wait()</code> method is called, the thread releases the lock on the object and enters a waiting state until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method.</p>
<p><code>notify()</code> wakes up one thread that is in the waiting state, while <code>notifyAll()</code> wakes up all waiting threads. When a thread wakes up again, it has to re-acquire the lock on the object. If another thread has the lock, then this thread needs to wait until the other thread releases the lock.</p>
<p>You can learn more about the <code>wait()</code> and <code>notify()</code> methods <a target="_blank" href="https://www.baeldung.com/java-wait-notify">here</a>.</p>
<h3 id="heading-how-to-communicate-between-threads-using-wait-and-notify">How to Communicate Between Threads using wait() and notify()</h3>
<p>Let's use the above methods. A producer needs to wait before it pushes an item if the queue is full. So, invoke the <code>wait()</code> method if the queue is at capacity. Similarly, the consumer needs to wait if the queue is empty.</p>
<p>To wake up threads from the waiting state, call <code>notifyAll()</code> after the producer publishes a message and the consumer consumer a message. This will notify all the waiting threads.</p>
<p>Here is the updated <code>publish()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size() == capacity){ 
        System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>); 
        wait(); 
    } 
    q.add(msg); 
    System.out.println(<span class="hljs-string">"Message published:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
    notifyAll(); 
}
</code></pre>
<p>And here's the updated <code>consume()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
        System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>); 
        wait(); 
     } 
    String msg = q.poll(); 
    System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
    notifyAll(); 
}
</code></pre>
<p><code>wait()</code> and <code>notify()</code> can throw <code>InterruptedException</code>, so we add a <code>throws</code> declaration to the methods.</p>
<h3 id="heading-output-1">Output:</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-132435-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output with Synchronization‌</em></p>
<p>This time, the output is more consistent and we are getting the expected behavior. The producer keeps publishing messages and the consumer consumes those messages.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-134924-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Producer waiting</em></p>
<p>Here, the queue is full and the producer waits for the consumer to consume a message. Only after that does the producer publish a new message.</p>
<h2 id="heading-producer-with-multiple-consumers">Producer with Multiple Consumers</h2>
<p>So far, we have tackled the problem with one producer and one consumer. In a real-world application, there could be multiple producers and consumers, all of them running in separate threads.</p>
<p>Let's add more consumer threads to see how we could handle this scenario:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span>(int i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">5</span>;i++){ 
    new Thread(new Consumer(data), <span class="hljs-string">"Consumer "</span>+i).start();
}
</code></pre>
<p>Here, we have created 5 consumer threads, labelled them, and started them one by one. But, this is not enough. There is an issue with the existing approach.</p>
<p>Let's reduce the consumer sleep time and run the code:</p>
<pre><code class="lang-java">Thread.sleep(<span class="hljs-number">500</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-203117.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multiple consumers issue</em></p>
<p>Here, after consumer 5 has consumed a message, the other consumers are able to consume even if the queue is empty.</p>
<p>The issue lies in the following condition:</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){
    wait();
}
</code></pre>
<p>Let's understand the workflow first. Consider Consumer 5 (C5) and Consumer 1 (C1). C5 secures the lock on the method and enters it. The queue is initially empty, so it releases the lock and waits for the producer. At the same time, C1 secures the lock and enters the method. It also waits for the producer.</p>
<p>So, C5 and C1 are waiting. The producer publishes a message. C5 and C1 are notified and they wake up. C5 reacquires the lock and proceeds to consume the message, while C1 waits for C5 to release the lock. Here, C1 is not waiting because of <code>wait()</code> – it has woken up and now it's waiting at the next line.</p>
<p>After C5 consumes the message and releases the lock, C1 continues and tries to consume the message. But the queue is empty now, so it receives null or throws an exception. This also happens with the other threads.</p>
<p>To prevent this, we need to check if the queue is empty once again. So, instead of using an <code>if</code> condition, we use a <code>while</code> loop like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">while</span>(q.size()==<span class="hljs-number">0</span>){
            wait();
        }
</code></pre>
<p>This checks if the queue is empty every time a thread wakes up. So, if multiple threads wake up at the same time, it should check if another thread has emptied the queue.</p>
<p>We do the same for checking if the queue is full.</p>
<pre><code class="lang-java"><span class="hljs-keyword">while</span>(q.size() == capacity){
            wait();
        }
</code></pre>
<p>This time, the code runs without any issues.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-204943.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multiple consumers correct output</em></p>
<p>Here is the complete code for <code>Data</code> class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Data</span> </span>{
    Queue&lt;String&gt; q;
    <span class="hljs-keyword">int</span> capacity;
    Data(<span class="hljs-keyword">int</span> cap) {
        q = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();
        capacity=cap;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        String name=Thread.currentThread().getName();
        <span class="hljs-keyword">while</span>(q.size() == capacity){
            System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>);
            wait();
        }
        q.add(msg);
        System.out.println(<span class="hljs-string">"Message published:: "</span>+msg);
        System.out.println(<span class="hljs-string">"Queue: "</span>+ q);
        System.out.println();
        notifyAll(); 
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        String name=Thread.currentThread().getName();
        <span class="hljs-keyword">while</span>(q.size()==<span class="hljs-number">0</span>){
            System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>);
            wait();
        }
        String msg = q.poll();
        System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
        System.out.println(<span class="hljs-string">"Queue: "</span>+ q);
        System.out.println();
        notifyAll();
    }
}
</code></pre>
<p>You can create any number of producers and consumers and test this code in multiple scenarios.</p>
<h2 id="heading-solution-using-java-concurrencys-blockingqueue-class">Solution using Java Concurrency's BlockingQueue Class</h2>
<p>So far you have learned what the producer-consumer problem is and how it can be solved. But, while working on real-time applications, we probably won't implement synchronization manually.</p>
<p>Instead, we can use the <code>BlockingQueue</code> class from <code>java.util.concurrent</code> package. The difference between <code>Queue</code> and <code>BlockingQueue</code> is that it waits for the queue to become non-empty before a message can be consumed. Similarly, it waits for the queue to have space before publishing a new message.</p>
<p>We can initialize the blocking queue in the following way:</p>
<pre><code class="lang-java">BlockingQueue&lt;String&gt; q = <span class="hljs-keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="hljs-number">10</span>);
</code></pre>
<p>This creates a blocking queue of capacity 10. To publish an item, we use the <code>put()</code> method, and to remove an item, we use the <code>take()</code> method.</p>
<p>Let's first use this in our Producer class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Producer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{
    BlockingQueue&lt;String&gt; q;
    <span class="hljs-keyword">final</span> String[] messages={<span class="hljs-string">"Hi!!"</span>, <span class="hljs-string">"How are you!!"</span>, <span class="hljs-string">"I love you!"</span>, <span class="hljs-string">"What's going on?!!"</span>, <span class="hljs-string">"That's really funny!!"</span>};
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Producer</span><span class="hljs-params">(BlockingQueue&lt;String&gt; q)</span> </span>{
        <span class="hljs-keyword">this</span>.q = q;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){
                Thread.sleep(<span class="hljs-number">500</span>);

                q.put(messages[i]);

                System.out.println(<span class="hljs-string">"Message published:: "</span>+messages[i]);
                i=(i+<span class="hljs-number">1</span>)%messages.length;
            }
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {}
    }

}
</code></pre>
<p>Here, we are not using a separate <code>Data</code> class with synchronized methods, since the <code>put()</code> and <code>take()</code> methods of <code>BlockingQueue</code> are synchronized. Here, if the queue is full, the <code>put()</code> method waits for a consumer to consume a message.</p>
<p>Similarly, let's update our Consumer class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Consumer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{
    BlockingQueue&lt;String&gt; q;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(BlockingQueue&lt;String&gt; q)</span> </span>{
        <span class="hljs-keyword">this</span>.q = q;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){
                Thread.sleep(<span class="hljs-number">1500</span>);

                String msg=q.take();

                String name=Thread.currentThread().getName();
                System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
            }
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {}
    }    
}
</code></pre>
<p>Here, if the queue is empty, the <code>take()</code> method waits for the producer to publish a message.</p>
<p>Let's create our <code>BlockingQueue</code> object and start these threads:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        BlockingQueue&lt;String&gt; q = <span class="hljs-keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="hljs-number">10</span>);
        Thread producer = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Producer(q));
        producer.start();
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">5</span>;i++){
            <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Consumer(q), <span class="hljs-string">"Consumer "</span>+i).start();
        }
    }

}
</code></pre>
<p>Here, we have one producer thread and 5 consumer threads. Let's see the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-28-115531.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output for BlockingQueue implementation</em></p>
<p>In the output, you can see that after consumers 1, 3, and 2 have consumed a message, the other consumers wait for a message to be published before consuming it.</p>
<p>There could be a few inconsistencies while printing these messages since the thread only stops at the <code>put()</code> or <code>take()</code> methods and not the <code>println()</code> statements. But the code runs properly. Again, the output will be different each time you run the code.</p>
<p>So, while working on big projects, you can use the <code>BlockingQueue</code> class. But it's important to understand how to deal with the whole producer-consumer problem from scratch. This is really helpful, especially during interviews, since you typically won't be allowed to use the <code>BlockingQueue</code> class.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned about an important problem in concurrency, the product-consumer problem. And you learned how you can solve it using multithreading in Java.</p>
<p>In total, we implemented four different approaches:</p>
<p>First, I started out with a very basic and straightforward implementation. Running the producer and consumer in separate threads helped achieve concurrency. But since they used the same message queue, there was a synchronization problem.</p>
<p>Therefore, in the next approach, we added synchronization to fix the issue. Then, we added more consumers who would all wait for the producer. There, we learned why it is important to check the full and empty conditions every time a thread wakes up.</p>
<p>After going through the whole implementation from scratch, we saw a simple way to solve the Producer-Consumer problem in Java using BlockingQueue. By understanding different approaches and their issues, you can get a better idea of how to tackle a problem. I hope this guide helps with your future endeavors.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Debouncing in JavaScript – Explained by Building Auto-Complete Functionality in React ]]>
                </title>
                <description>
                    <![CDATA[ Hi readers, I hope you are doing great! I am back with another tutorial on web development. If you are someone who enjoys developing web apps with JavaScript and React, then this post is for you. When you roll out a new app into production, you want ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deboucing-in-react-autocomplete-example/</link>
                <guid isPermaLink="false">66d85149e86088251dd27bc0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 12 Feb 2024 23:23:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/photo-1550063873-ab792950096b.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi readers, I hope you are doing great! I am back with another tutorial on web development. If you are someone who enjoys developing web apps with JavaScript and React, then this post is for you.</p>
<p>When you roll out a new app into production, you want to make sure that it's user friendly. A website's performance is a key part of the user experience. Every user wants the website and its contents to load quickly. Each and every second is valuable and could result into a user never visiting your website again.</p>
<p>In this guide, we are going to understand a very important technique in JavaScript known as debouncing. Then, I will show you how to implement the autocomplete functionality in React with debouncing.</p>
<p>Now, in order to get the most out of this tutorial, I am assuming you have a basic knowledge of JavaScript. If you need to get started or review, here are a couple resources for you:</p>
<ul>
<li><p>Learn JavaScript basics – <a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-for-beginners/">handbook for beginners</a></p>
</li>
<li><p>The freeCodeCamp <a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-with-new-data-structures-and-algorithms-certification-projects/">JavaScript Algorithms and Data Structures certification</a></p>
</li>
</ul>
<h2 id="heading-table-of-contents"><strong>Table of Contents:</strong></h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-debouncing">What is Debouncing?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-debouncing-in-javascript">How to Implement Debouncing in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-case-of-debouncing">Use Case of Debouncing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-debouncing">What is Debouncing?</h2>
<p>Debouncing is a strategy used to improve the performance of a feature by controlling the time at which a function should be executed.</p>
<p>Debouncing accepts a function and transforms it in to an updated (debounced) function so that the code inside the original function is executed after a certain period of time.</p>
<p>If the debounced function is called again within that period, the previous timer is reset and a new timer is started for this function call. The process repeats for each function call.</p>
<p>An example will help you understand better. Let's take a function <code>fun()</code>. We want this function to execute after 500ms.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a function'</span>)
}
</code></pre>
<p>After debouncing, a new function <code>debouncedFun()</code> is returned. Now, whenever you call <code>debouncedFun()</code>, it will be called after 500ms.</p>
<p>If you call it again within the next 500ms after first calling it, the previous timer is reset and a new timer is started for the second function call. The process repeats if you keep calling the function within 500ms.</p>
<h2 id="heading-how-to-implement-debouncing-in-javascript">How to Implement Debouncing in JavaScript</h2>
<p>Let's understand how to implement debouncing in JavaScript. First, we'll go over our requirements. What behavior do we want from the debounced function?</p>
<ul>
<li><p>Delay the function execution by a certain time, <code>delay</code>.</p>
</li>
<li><p>Reset the timer if the function is called again.</p>
</li>
</ul>
<p>To debounce a function, we'll have a separate function that accepts the function reference and the delay as parameters, and returns a debounced function.</p>
<pre><code class="lang-python">function debounce(func, delay) {
      <span class="hljs-keyword">return</span> () =&gt; {}   // <span class="hljs-keyword">return</span> debounced function
}
</code></pre>
<p>This function will only be called once to return a debounced function and that, in turn, will be used in the subsequent code.</p>
<p>To delay a function by some milliseconds, we can simply use the <code>setTimeout</code> function in JavaScript.</p>
<pre><code class="lang-python">function debounce(func, delay) {
    <span class="hljs-keyword">return</span> () =&gt; {
        setTimeout(() =&gt; {
            func()
        }, delay)
    }
}
</code></pre>
<p>This delays the function call by <code>delay</code> milliseconds. But this is incomplete as it only satisfies the first requirement. How do we achieve the second behaviour?</p>
<p>Let's create a variable <code>timeout</code> and assign it to the return value of <code>setTimeout</code> method. The <code>setTimeout</code> method returns a unique identifier to the timeout, which is held by <code>timeout</code> variable.</p>
<pre><code class="lang-python">function debounce(func, delay) {
    let timeout=null
    <span class="hljs-keyword">return</span> () =&gt; {
        timeout=setTimeout(() =&gt; {
            func()
        }, delay)
    }
}
</code></pre>
<p>Each time you invoke <code>setTimeout</code>, the ID is different. We will use this <code>timeout</code> variable to reset the timer.</p>
<p>But how do we get access to <code>timeout</code> from outside the <code>debounce()</code> method? As mentioned before, <code>debounce()</code> is only used once to return a debounced function. This, in turn, performs the debouncing logic.</p>
<p>Then, how does the debounced function have access to <code>timeout</code> even if it is used outside the <code>debounce()</code> function? Well, it uses a concept called closure.</p>
<h3 id="heading-whats-a-closure-in-javascript">What's a closure in JavaScript?</h3>
<p>In JavaScript, an inner function always has access to the local variables of the outer function. In our case, the inner function has access to <code>timeout</code> that has function level scope in the <code>debounce()</code> method.</p>
<p>But when the outer function returns this inner function, the inner function still holds a reference to the local variables of the outer function long after the outer function has finished execution. This is the concept of a closure.</p>
<p>Let's understand closures with an example.</p>
<pre><code class="lang-python">function outerFunction() {
  const x = <span class="hljs-number">5</span>;

  <span class="hljs-keyword">return</span> () =&gt; {
    console.log(x);
  }
}

const inner = outerFunction();

inner(); // prints <span class="hljs-number">5</span>

// console.log(x)   Throws reference error
</code></pre>
<p>Here, if we call <code>inner()</code>, the code runs without any errors and prints 5. But, if we try to access <code>x</code> directly, JavaScript throws a reference error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-141749.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>JavaScript Reference Error</em></p>
<p>Here, <code>inner()</code> closes over <code>x</code> and only this function can use the variable and no one other one can. We cannot access the variable explicitly.</p>
<p>You can check out <a target="_blank" href="https://www.freecodecamp.org/news/closures-in-javascript/">this beginner-friendly tutorial</a> to learn more about closures.</p>
<h3 id="heading-back-to-debouncing">Back to Debouncing</h3>
<p>Let's get back to where we left off:</p>
<pre><code class="lang-python">function debounce(func, delay) {
    let timeout=null
    <span class="hljs-keyword">return</span> () =&gt; {
        timeout=setTimeout(() =&gt; {
            func()
        }, delay)
    }
}
</code></pre>
<p>Here, JavaScript uses a closure to hold access to <code>timeout</code> every time we use the debounced function.</p>
<p>Let's use this to our advantage. Since <code>debouncedFun()</code> has access to the same <code>timeout</code> variable in every function call, we can add a condition to check whether a previous timeout exists. We can simply do this with a null check, <code>if(timeout !== null)</code> or <code>if(timeout)</code>.</p>
<p>Then, we use the <code>clearTimeout()</code> method to cancel the previous timeout, thus resetting the timer.</p>
<p>Add the following statement before starting a new timeout:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span>(timeout) 
    clearTimeout(timeout)
</code></pre>
<p>Once the timeout is reset, a new timeout is started for the current function call, whose ID is then assigned to <code>timeout</code>. The process is repeated for the subsequent function calls who have access to the same <code>timeout</code> due to closures.</p>
<pre><code class="lang-python">function debounce(func, delay) {
    let timeout=null
    <span class="hljs-keyword">return</span> () =&gt; {
        <span class="hljs-keyword">if</span>(timeout) clearTimeout(timeout)

        timeout=setTimeout(() =&gt; {
            func()
        }, delay)
    }
}
</code></pre>
<p>With this, we have satisfied our second requirement – that is, resetting the timer and starting a new one. It's time to use this debounced function.</p>
<p>Let's pass <code>fun()</code> to the <code>debounce()</code> method with a delay of 500ms.</p>
<pre><code class="lang-python">const debouncedFun = debounce(fun, <span class="hljs-number">500</span>)
</code></pre>
<p><code>debouncedFun()</code> is basically <code>fun()</code> with debouncing behaviour. Let's call this function at different time intervals to test our functionality.</p>
<pre><code class="lang-python">debouncedFun()

setTimeout(debouncedFun, <span class="hljs-number">300</span>)

setTimeout(debouncedFun, <span class="hljs-number">900</span>)
</code></pre>
<p>The first function call is made instantly. The other two are made after 300ms and 900ms respectively. Can you guess the output?</p>
<p>The code prints <code>This is a function</code> two times. Let's understand why. Here, after the first call is made, <code>fun()</code> is scheduled to execute after 500ms. But the second one is made in 300ms which resets the timer and starts a new one.</p>
<p>500ms have passed and the <code>fun()</code> method executes. Then, at 900ms, another function call is made. This again executes <code>fun()</code> after 500ms.</p>
<p>There is still a small improvement we should make. Our logic does not consider function arguments. Let's replace <code>fun()</code> with <code>fun(a, b)</code>.</p>
<pre><code class="lang-python">function fun(a, b) {
    console.log(`This <span class="hljs-keyword">is</span> a function <span class="hljs-keyword">with</span> arguments ${a} <span class="hljs-keyword">and</span> ${b}`)
}
</code></pre>
<p>To incorporate arguments while debouncing, return a debounced function that accepts arguments.</p>
<pre><code class="lang-python">function debounce(func, delay) {
    let timeout=null
    <span class="hljs-keyword">return</span> (...args) =&gt; {
        <span class="hljs-keyword">if</span>(timeout) clearTimeout(timeout)

        timeout=setTimeout(() =&gt; {
            func(...args)
            timeout=null
        }, delay)
    }
}
</code></pre>
<p>By using the spread operator, any arguments passed to the debounced function will be stored as an array in the <code>args</code> variable. Then, spread out the same <code>args</code> array to call the actual function with the arguments passed.</p>
<pre><code class="lang-python">const debouncedFun=debounce(fun, <span class="hljs-number">500</span>)
debouncedFun(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)
</code></pre>
<p>The above code prints <code>This is a function with arguments 2 and 3</code> after 500ms.</p>
<h2 id="heading-use-case-of-debouncing">Use Case of Debouncing</h2>
<p>Let's see how debouncing is used in practical applications. The most common use case of debouncing is the autocomplete functionality. You must have seen many websites where you type into an input field and it shows a list of results as you type them.</p>
<p>Here's an example from Google Search:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-163240.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Google Search Autocomplete after typing in "Top 10"</em></p>
<p>Google search shows the most recent and commonly searched terms. The information is mostly fetched from the browser cache. But, several websites make API calls to backend server to fetch the data from a database.</p>
<p>This can easily be implemented by adding an <code>onchange</code> event to the <code>input</code> element and implementing the fetch logic in the event handler. But there's a slight issue with this.</p>
<p>Consider the following example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-163930.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API Request made for each input value</em></p>
<p>When I type the word <em>absolute</em>, an API request is made every time the value of the input field changes. We are making 8 API requests in very few milliseconds which puts a lot of load on the backend server and could cause performance issues.</p>
<p>Ideally, we want to show the auto-complete results some time after the user has finished typing. Here, the user has typed <em>absolute</em> in one go, so instead of showing results every time the input changes, we could show them once the user has finished typing – that is, we could add some delay between the input change and the results being displayed.</p>
<p>So, we only make the API calls when the user finishes typing their word and not on every input change. This reduces the number of API calls and improves performance. We can achieve this behavior with debouncing.</p>
<p>Let's understand how to implement the autocomplete functionality in React.</p>
<h3 id="heading-auto-complete-example">Auto-complete example</h3>
<p>Use <code>create-react-app</code> (or a modern build tool like Vite) to create the project. Remove the existing boilerplate code. There is no need to install any additional dependencies. Run <code>npm start</code> command to start the project. You can find the complete code on <a target="_blank" href="https://github.com/KunalN25/react-debouncing">GitHub</a>.</p>
<p>I have set up a Node server to fetch data for the app. You can find it in the Git repo. Run the <code>node server</code> command to start it. I am not going to show the Node.js code as it's out of the scope of this tutorial.</p>
<p>Let's get started with the implementation. We will write a simple autocomplete functionality. The app should show a list of cities that contain an input string typed by the user.</p>
<h4 id="heading-app-component">App Component</h4>
<p>We'll first need an <code>input</code> element to accept user input and a <em>results container</em> for the search results. Attach an event handler to the <code>input</code> element which is an <code>async</code> function since it will include the fetching logic.</p>
<pre><code class="lang-python">function App() {
    const [data, setData] = useState(null)

    const loadData = <span class="hljs-keyword">async</span> (event) =&gt; {

    }
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"App"</span>&gt;
            &lt;input type=<span class="hljs-string">"text"</span> onChange={(e) =&gt; loadData(e)}/&gt;
            {data &amp;&amp; data.length !== <span class="hljs-number">0</span> &amp;&amp;
            &lt;div className=<span class="hljs-string">"results-container"</span>&gt;
                {data.map(item =&gt; (
                    &lt;div key={item.id} className=<span class="hljs-string">"result-item"</span>&gt;
                        &lt;p&gt; {item.city} &lt;/p&gt;
                    &lt;/div&gt;
                ))}
            &lt;/div&gt;}
        &lt;/div&gt;
    );
}
</code></pre>
<p>The data will be stored as state and the results will only be shown if the data is non-empty. I'll skip over the CSS for this tutorial, you can find it in the <a target="_blank" href="https://github.com/KunalN25/react-debouncing">Git Repo</a>.</p>
<h4 id="heading-event-handler">Event Handler</h4>
<p>The <code>loadData()</code> function fetches our data and stores the response as state.</p>
<pre><code class="lang-python">const loadData = <span class="hljs-keyword">async</span> (event) =&gt; {
    const value=event.target.value
    <span class="hljs-keyword">if</span>(value === <span class="hljs-string">''</span>) {
        setData(null)
        <span class="hljs-keyword">return</span>
    }
    const response=<span class="hljs-keyword">await</span> fetch(`http://localhost:<span class="hljs-number">8000</span>/data/${value}`)
    const res=<span class="hljs-keyword">await</span> response.json()
    setData(res)
}
</code></pre>
<p>If no value is entered, simply exit the function. Else, make the request to the node server endpoint. This function is called every time the input changes, so we will debounce this function.</p>
<h4 id="heading-debounce-implementation-using-a-custom-hook">Debounce Implementation using a Custom Hook</h4>
<p>We will write the debouncing logic inside a custom hook. The advantage of custom hooks is that you can re-use the same logic throughout your application. It is highly advisable to do so.</p>
<p>Create a new folder <code>custom-hooks</code> and inside it, create a file <code>useDebounce.js</code>. As explained before, the <code>useDebounce()</code> method should take a function and delay as parameters and return the debounced function.</p>
<pre><code class="lang-python">const useDebounce = (func, delay) =&gt; {
    let timeout=null

    <span class="hljs-keyword">return</span> (...args) =&gt; {
        <span class="hljs-keyword">if</span>(timeout) clearTimeout(timeout)

        timeout=setTimeout(() =&gt; {
            func(...args)
        }, delay)
    }
}

export default useDebounce
</code></pre>
<p>Now, inside the app component, call this method once to get <code>loadDataDebounced()</code>.</p>
<pre><code class="lang-python">const loadDataDebounced = useDebounce(loadData, <span class="hljs-number">400</span>)
</code></pre>
<p>We'll use this new method as the event handler for the <code>input</code> element.</p>
<pre><code class="lang-python">&lt;input type=<span class="hljs-string">"text"</span> onChange={(e) =&gt; loadDataDebounced(e)}/&gt;
</code></pre>
<h4 id="heading-output">Output</h4>
<p>Enter a search string inside the <code>input</code> element to test our code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-190240.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>On-screen output</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-09-191234.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see in the Network tab, only one request is getting sent instead of three. This makes the search performance much better.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned what debouncing is and how it is implemented. Debouncing delays the function execution by a certain time and resets the previous timer if the function is called again.</p>
<p>Debouncing uses the important concept of closures. I took a slight detour from the implementation to explain what closure is. It can be a confusing concept for beginners, so take your time understanding it. Closures allow you to work with local variables even after a function has finished execution.</p>
<p>After that, I showed you a popular use case of debouncing, the auto-complete functionality. The performance of the feature can be improved with debouncing. I also showed you how to implement auto-complete in React and use debouncing with custom hooks. I hope this helps you in future projects.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, Goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java Project – How to Build a Simple Parking Lot Management System ]]>
                </title>
                <description>
                    <![CDATA[ Hello everyone! It's good to be back with another tutorial – this time on Java, one of the most popular programming languages out there today. Java is used by developers and enterprises to build powerful applications that serve many different purpose... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-project-parking-lot-management-system/</link>
                <guid isPermaLink="false">66d8515a7211ea6be29e1b81</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ projects ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Wed, 07 Feb 2024 00:25:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/java-article-image.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello everyone! It's good to be back with another tutorial – this time on Java, one of the most popular programming languages out there today.</p>
<p>Java is used by developers and enterprises to build powerful applications that serve many different purposes. The object-oriented nature of Java makes writing clean, modular, reusable code very easy.</p>
<p>If you are not comfortable with Java yet, there are many great resources online that can help you get started. You can check out <a target="_blank" href="https://www.freecodecamp.org/news/learn-java-free-java-courses-for-beginners/">this collection of resources</a> put together by one of our freeCodeCamp staff. <a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-java-programming/">Here's a beginner-friendly Java course</a>. And <a target="_blank" href="https://www.javatpoint.com/java-tutorial">here's another helpful tutorial</a> to help you work on the basics. It's never too late!</p>
<p>In this tutorial, we are going to build a simple command-line application for a parking lot system. I'll start with the requirements first, then list down the classes needed and explain the workflow of the application. After this, I will show you how to implement each functionality.</p>
<h2 id="heading-heres-what-well-cover">Here's What We'll Cover:</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-the-project">How to Set Up the Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-project-requirements">Project Requirements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-java-classes">Java Classes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-application-workflow">Application Workflow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-the-application">How to Build the Application</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-the-app">How to Test the Application</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-future-scope">Future Scope</a></p>
</li>
</ol>
<h2 id="heading-how-to-set-up-the-project">How to Set Up the Project</h2>
<p>You need to have Java 8 installed in your system. If you don't, then download it from <a target="_blank" href="https://www.oracle.com/java/technologies/downloads/">here</a> and follow <a target="_blank" href="https://phoenixnap.com/kb/install-java-windows">this</a> installation guide. Also, install <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> and add the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=redhat.java">Language Support for Java</a> extension on VS Code.</p>
<p>There's no need to set up a database connection, an external server, or a framework. We'll use an in-memory data structure to store the data. Also, we are not going to create a user interface, as the focus is only on the business logic.</p>
<p>With that out of the way, we are ready to start.</p>
<h2 id="heading-project-requirements">Project Requirements</h2>
<p>Our goal is to create an application for a parking lot system. As everyone visualizes projects differently, there may be many features that come into your mind.</p>
<p>But before jumping into the implementation, we first need to lay down specific requirements. It's always important to start with the basic requirements first, so that's what we'll do here.</p>
<p>Here is a list of all the requirements:</p>
<ul>
<li><p>A parking lot should have a parking lot ID, number of floors, and number of slots on each floor.</p>
</li>
<li><p>Each slot in the parking lot has a type of vehicle that can park there. Valid types are <em>car, bike,</em> and <em>truck.</em> You can include any vehicle type as per your needs. You can also decide which slots should go to each type. Here, I am assigning the first slot on each floor to a truck, the next two for bikes, and rest for cars.</p>
</li>
<li><p>When a vehicle pulls into the parking lot, the application takes the vehicle's type, registration number, and its color. You can also have additional details like the vehicle's name, the driver's name, and so on.</p>
</li>
<li><p>After that, a slot is assigned to the vehicle. The selection strategy could be anything you want. Here, we will choose the lowest floor and earliest available slot.</p>
</li>
<li><p>When a vehicle is assigned a slot, the app should return a ticket. The ticket should be a string of the form . For example, the vehicle parked on floor 2, slot 5 would be <em>PR123_2_5.</em></p>
</li>
<li><p>To unpark the vehicle, the user should present the valid ticket. After that, the vehicle is removed from the slot.</p>
</li>
<li><p>The app should be able to display the number of available slots and a list of available and unavailable slots for a specific vehicle type.</p>
</li>
</ul>
<h2 id="heading-java-classes">Java Classes</h2>
<p>Let's understand how we are going to design the application. Since it is a command line application, we are only going to write the business logic of a parking lot and display outputs on a console.</p>
<p>We will have separate classes representing the entities of our application: <code>Vehicle</code> and <code>Slot</code>. Then, we'll create a <code>ParkingLot</code> class that contains the core business logic of our application. Our main driver class will interact with this class for all the functionalities.</p>
<p>Now, let's define our classes. Each class will have a constructor to initialize their fields.</p>
<p><strong>Vehicle class:</strong></p>
<ul>
<li><code>type</code>, <code>registration</code>, <code>color</code> (All are of string type)</li>
</ul>
<p><strong>Slot class:</strong></p>
<ul>
<li><p><code>type</code> (string)</p>
</li>
<li><p><code>vehicle</code> (Vehicle): type of vehicle parked in the slot</p>
</li>
<li><p><code>ticketId</code> (string): ticket id assigned to the vehicle parked in this slot, initially null.</p>
</li>
</ul>
<p><strong>ParkingLot class:</strong></p>
<p><strong>Fields</strong>:</p>
<ul>
<li><p><code>parkingLotId</code> (string)</p>
</li>
<li><p><code>slots</code> (List&lt;List&gt;): This is a list of all the slots in the parking lot. The list of lists represents slots on multiple floors. The floors and slots are numbered according to the list index.</p>
</li>
</ul>
<p><strong>Constructor</strong>: <code>ParkingLot(parkingLotId, nfloors, noOfSlotsPerFlr)</code></p>
<p><strong>Methods</strong>:</p>
<ul>
<li><p><code>parkVehicle(type, regNo, color)</code>: takes all the parameters of a vehicle, assigns a slot, and returns the ticket</p>
</li>
<li><p><code>unPark(ticketId)</code>: takes the ticket id and removes the vehicle from the slot</p>
</li>
<li><p><code>getNoOfOpenSlots(type)</code>: returns the number of slots for vehicle type</p>
</li>
<li><p><code>displayOpenSlots(type)</code>: displays all open slots for vehicle type</p>
</li>
<li><p><code>displayOccupiedSlots(type)</code>: displays all occupied slots for vehicle type</p>
</li>
</ul>
<p>This will contain our core business logic including the methods that will be exposed to the client i.e. the main method in our case. The initialization logic inside the constructor works differently as compared to the <code>Vehicle</code> and <code>Slot</code> class.</p>
<p>You will learn more about these classes in the implementation section.</p>
<h2 id="heading-application-workflow">Application Workflow</h2>
<p>Now that we have our classes defined, let's understand the workflow of our application.</p>
<p>When a vehicle pulls into the parking lot, the system takes in the vehicle details and looks for an available slot. If it finds an open slot, it assigns that slot to the vehicle and returns a ticket.</p>
<p>This is handled by the <code>parkVehicle()</code> method. If a slot is not available, then the method prints an error message.</p>
<p>Now, if the vehicle wants to unpark, it has to show the ticket. The system parses the ticket, finds out which slot the vehicle is parked in and frees up the slot. The <code>unPark()</code> method takes in the ticket and frees up the corresponding slot.</p>
<p>Let's dive into the code now.</p>
<h2 id="heading-how-to-build-the-application">How to Build the Application</h2>
<p>Let's first write our <code>Vehicle</code> and <code>Slot</code> classes with the fields mentioned previously:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    String type;
    String registration;
    String color;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Vehicle</span><span class="hljs-params">(String type, String registration, String color)</span> </span>{
        <span class="hljs-keyword">this</span>.type = type;
        <span class="hljs-keyword">this</span>.registration = registration;
        <span class="hljs-keyword">this</span>.color = color;
    }
}
</code></pre>
<pre><code class="lang-python">public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Slot</span> {
    <span class="hljs-title">String</span> <span class="hljs-title">type</span>;
    <span class="hljs-title">Vehicle</span> <span class="hljs-title">vehicle</span>;
    <span class="hljs-title">String</span> <span class="hljs-title">ticketId</span>;
    <span class="hljs-title">public</span> <span class="hljs-title">Slot</span>(<span class="hljs-params">String type</span>) {
        <span class="hljs-title">this</span>.<span class="hljs-title">type</span> = <span class="hljs-title">type</span>;
        <span class="hljs-title">this</span>.<span class="hljs-title">vehicle</span>=<span class="hljs-title">null</span>;
        <span class="hljs-title">this</span>.<span class="hljs-title">ticketId</span>=<span class="hljs-title">null</span>;
    }
}</span>
</code></pre>
<p>Now, let's implement the <code>ParkingLot</code> class. We have discussed the fields and methods the class will contain. Let's write the fields first.</p>
<pre><code class="lang-python">public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParkingLot</span> {
    <span class="hljs-title">String</span> <span class="hljs-title">parkingLotId</span>;
    <span class="hljs-title">List</span>&lt;<span class="hljs-title">List</span>&lt;<span class="hljs-title">Slot</span>&gt;&gt; <span class="hljs-title">slots</span>;

    ... <span class="hljs-title">constructor</span> <span class="hljs-title">and</span> <span class="hljs-title">methods</span> ...
 }</span>
</code></pre>
<p>I'll show you, step by step, how to implement each functionality.</p>
<h3 id="heading-initialize-the-class">Initialize the Class</h3>
<p>Initialize the <code>ParkingLot</code> class through the constructor. This is where we build our parking lot. As mentioned before, the parking lot will have a given number of floors and number of slots per floor.</p>
<pre><code class="lang-java">ParkingLot(String parkingLotId, <span class="hljs-keyword">int</span> nfloors, <span class="hljs-keyword">int</span> noOfSlotsPerFlr) {
        ... code here ...
    }
</code></pre>
<p>Start by setting the parking lot id.</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.parkingLotId=parkingLotId;
</code></pre>
<p>Then, initialize all the slots. On each floor, the first slot goes to truck, the next two go to bike, and the rest are for cars.</p>
<pre><code class="lang-java">slots = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;nfloors;i++){
    slots.add(<span class="hljs-keyword">new</span> ArrayList&lt;&gt;());
    List&lt;Slot&gt; floorSlots = slots.get(i);
    floorSlots.add(<span class="hljs-keyword">new</span> Slot(<span class="hljs-string">"truck"</span>));
    floorSlots.add(<span class="hljs-keyword">new</span> Slot(<span class="hljs-string">"bike"</span>));
    floorSlots. add(<span class="hljs-keyword">new</span> Slot(<span class="hljs-string">"bike"</span>));

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j=<span class="hljs-number">3</span>;j&lt;noOfSlotsPerFlr;j++){
        slots.get(i).add(<span class="hljs-keyword">new</span> Slot(<span class="hljs-string">"car"</span>));
    }
}
</code></pre>
<p>Here, we have done simple initialization for each <code>Slot</code> object in the list.</p>
<h3 id="heading-park-the-vehicle">Park the Vehicle</h3>
<p>Let's implement the <code>parkVehicle()</code> method now.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">parkVehicle</span><span class="hljs-params">(String type, String regNo, String color)</span> </span>{
        ... Implementation here ...
    }
</code></pre>
<p>First, create a <code>Vehicle</code> object with the given details.</p>
<pre><code class="lang-java">Vehicle vehicle = <span class="hljs-keyword">new</span> Vehicle(type, regNo, color);
</code></pre>
<p>Loop over the entire slots list and find the first empty slot. To determine whether a slot is empty or not, check if the slot can take the given vehicle type and if the slot's vehicle field is null (meaning it is empty).</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>; i&lt;slots.size();i++){
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j=<span class="hljs-number">0</span>;j&lt;slots.get(i).size(); j++){
                Slot slot = slots.get(i).get(j);
                <span class="hljs-keyword">if</span>(slot.type == type &amp;&amp; slot.vehicle == <span class="hljs-keyword">null</span>) {
                    ... assign the slot here ...
                }
            }
        }
</code></pre>
<p>To assign this slot to the vehicle, just set the <code>vehicle</code> field to the <code>Vehicle</code> object we created above. Then, generate and return a ticket using the floor and slot numbers.</p>
<pre><code class="lang-java">slot.vehicle=vehicle;
slot.ticketId=generateTicketId(i+<span class="hljs-number">1</span>, j+<span class="hljs-number">1</span>);
<span class="hljs-keyword">return</span> slot.ticketId;
</code></pre>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">private</span> String <span class="hljs-title">generateTicketId</span><span class="hljs-params">(<span class="hljs-keyword">int</span> flr, <span class="hljs-keyword">int</span> slno)</span></span>{
        <span class="hljs-keyword">return</span> parkingLotId + <span class="hljs-string">"_"</span> + flr + <span class="hljs-string">"_"</span> + slno;
    }
</code></pre>
<p>This method does not need to be exposed outside the class, so it's private.</p>
<p>If a slot is not available, return null or throw an exception. Do this after the for loop has ended.</p>
<pre><code class="lang-java">System.out.println(<span class="hljs-string">"NO slot available for given type"</span>);
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
</code></pre>
<h3 id="heading-unpark-the-vehicle">Unpark the Vehicle</h3>
<p>To unpark the vehicle, parse the ticket id to get the floor and slot number where the car is parked.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">unPark</span><span class="hljs-params">(String ticketId)</span></span>{
        String[] extract = ticketId.split(<span class="hljs-string">"_"</span>);
        <span class="hljs-keyword">int</span> flr_idx=Integer.parseInt(extract[<span class="hljs-number">1</span>])-<span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> slot_idx=Integer.parseInt(extract[<span class="hljs-number">2</span>])-<span class="hljs-number">1</span>;

         ...
    }
</code></pre>
<p>Surround the parsing logic with a try-catch in case the user passes an invalid ticket id.</p>
<p>With the floor and slot number, find the slot where the vehicle is parked and un-assign the vehicle.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span>(int i=<span class="hljs-number">0</span>; i&lt;slots.size();i++){
            <span class="hljs-keyword">for</span>(int j=<span class="hljs-number">0</span>;j&lt;slots.get(i).size(); j++){
                <span class="hljs-keyword">if</span>(i==flr_idx &amp;&amp; j==slot_idx) {
                    Slot slot = slots.get(i).get(j);
                    slot.vehicle=null;
                    slot.ticketId=null;
                    System.out.println(<span class="hljs-string">"Unparked vehicle"</span>);
                }
            }
        }
</code></pre>
<h3 id="heading-display-parking-lot-information">Display Parking Lot Information</h3>
<p>We have defined three methods to display parking lot information in different forms.</p>
<p><strong>Return the number of open slots for a vehicle type.</strong></p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getNoOfOpenSlots</span><span class="hljs-params">(String type)</span></span>{
        <span class="hljs-keyword">int</span> count=<span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span>(List&lt;Slot&gt; floor: slots){
            <span class="hljs-keyword">for</span>(Slot slot: floor){
                <span class="hljs-keyword">if</span>(slot.vehicle == <span class="hljs-keyword">null</span> &amp;&amp; slot.type.equals(type)) count++;
            }
        }

        <span class="hljs-keyword">return</span> count;
    }
</code></pre>
<p>Here, we loop over all the slots and check two conditions. First, we check if the <code>vehicle</code> field is null indicating an empty slot. And then we check if the type of the slot matches with the vehicle type requested by the client.</p>
<p>We then simply return the number of empty slots for the give type.</p>
<p><strong>Display all the open slots for vehicle type:</strong></p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">displayOpenSlots</span><span class="hljs-params">(String type)</span></span>{
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;slots.size();i++){
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j=<span class="hljs-number">0</span>;j&lt;slots.get(i).size();j++){
                Slot slot=slots.get(i).get(j);
                <span class="hljs-keyword">if</span>(slot.vehicle == <span class="hljs-keyword">null</span> &amp;&amp; slot.type.equals(type)) 
                    System.out.println(<span class="hljs-string">"Floor "</span> + (i+<span class="hljs-number">1</span>) + <span class="hljs-string">" slot "</span> + (j+<span class="hljs-number">1</span>));
            }
        }   
    }
</code></pre>
<p>This is an enhancement over the previous function. Instead of the count, we are returning the actual empty slots with floor and slot no.</p>
<p><strong>Display all occupied slots for vehicle type:</strong></p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">displayOccupiedSlots</span><span class="hljs-params">(String type)</span></span>{
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;slots.size();i++){
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j=<span class="hljs-number">0</span>;j&lt;slots.get(i).size();j++){
                Slot slot=slots.get(i).get(j);
                <span class="hljs-keyword">if</span>(slot.vehicle != <span class="hljs-keyword">null</span> &amp;&amp; slot.type.equals(type)) 
                    System.out.println(<span class="hljs-string">"Floor "</span> + (i+<span class="hljs-number">1</span>) + <span class="hljs-string">" slot "</span> + (j+<span class="hljs-number">1</span>));
            }
        }   
    }
</code></pre>
<p>Here, we check the opposite condition for the <code>vehicle</code> field. If it is not null, then that slot is occupied by a vehicle. We then check if the vehicle type matches with the requested type and then display the floor and slot no.</p>
<p>With this, we have our basic implementation of a parking lot. It is time to test out each functionality.</p>
<h2 id="heading-how-to-test-the-app">How to Test the App</h2>
<p>Since we do not have a UI or a testing framework, we are going to test each functionality manually from the driver code. Just like any Java application, ours will also start from the main method.</p>
<p>First, let's create a <code>ParkingLot</code> object. Each functionality of the parking lot will be accessed through this object.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> nFloors=<span class="hljs-number">4</span>;
<span class="hljs-keyword">int</span> nSlotsPerFloor=<span class="hljs-number">6</span>;
ParkingLot parkingLot = <span class="hljs-keyword">new</span> ParkingLot(<span class="hljs-string">"PR1234"</span>, nFloors, nSlotsPerFloor);
</code></pre>
<p>This creates a parking lot with 4 floors and 6 slots per floor, for a total of 24 slots.</p>
<pre><code class="lang-java">parkingLot.getNoOfOpenSlots(<span class="hljs-string">"car"</span>)

String ticket1 = parkingLot.parkVehicle(<span class="hljs-string">"car"</span>, <span class="hljs-string">"MH-03"</span>, <span class="hljs-string">"red"</span>);
String ticket2 = parkingLot.parkVehicle(<span class="hljs-string">"car"</span>, <span class="hljs-string">"MH-04"</span>, <span class="hljs-string">"purple"</span>);

parkingLot.displayOccupiedSlots(<span class="hljs-string">"car"</span>);
</code></pre>
<p>First, we display the number of open slots available for a car. Then, we park two cars and get the tickets. After parking, we display the occupied slots.</p>
<p>To run the program, click the run button in the top right.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/blg1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>VS Code Editor</em></p>
<p>This gives the following output.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output for the above test cases</em></p>
<p>Here, you can see the first available slots were assigned to the car.</p>
<p>Now, unpark the second vehicle and display the occupied slots.</p>
<pre><code class="lang-java">parkingLot.unPark(ticket2);
parkingLot.displayOccupiedSlots(<span class="hljs-string">"car"</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>After Unparking</em></p>
<p>Let's try parking a truck now. Display available slots for a truck, park the truck, and display occupied slots.</p>
<pre><code class="lang-java">parkingLot.displayOpenSlots(<span class="hljs-string">"truck"</span>);
parkingLot.parkVehicle(<span class="hljs-string">"truck"</span>, <span class="hljs-string">"MH-01"</span>, <span class="hljs-string">"black"</span>);
parkingLot.displayOccupiedSlots(<span class="hljs-string">"truck"</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-36.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output after parking a truck</em></p>
<p>I'll park three more trucks and then try parking another one. Since there are no more truck slots available, it shows the following message:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-38.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output if the parking lot is full</em></p>
<h2 id="heading-future-scope">Future Scope</h2>
<p>In this article, we have created a very basic command-line application for a parking lot. The application only does one thing – assigning and un-assigning a vehicle from a parking slot. But there are many other things you can add to this basic app:</p>
<ul>
<li><p>Use encapsulation wherever possible. Technically, this should not come under future scope. I have not used encapsulation here as I only wanted to focus on the design and logical part. But while working on actual applications, remember to encapsulate all the fields and access them through getters and setters.</p>
</li>
<li><p>Implement proper exception handling for scenarios where a slot is not available, a vehicle type is not allowed, or the ticket is invalid.</p>
</li>
<li><p>You can add more types of vehicles to the parking lot and use a different strategy to assign slot types.</p>
</li>
<li><p>You can use a different strategy to find out the first available slot.</p>
</li>
<li><p>You can expose all the logic we have discussed here as a backend service and create a UI for your parking lot with a database as well.</p>
</li>
</ul>
<p>You can find the code on GitHub <a target="_blank" href="https://github.com/KunalN25/parking-lot-app">here</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this post, we created a simple command-line application with Java from the requirements. From the list of requirements, we determined the design of the application and defined the classes needed. Then, we understood the workflow of our application.</p>
<p>After finalizing the design and the workflow, we jumped into the implementation. This simple application was an example of how you outline the requirements and based on those requirements, figure out the design and workflow of your application.</p>
<p>Before writing the code, you should know what classes you are going to use and the purpose of each class. This is true no matter how small or big an application you want to make. I hope this helps in your future projects.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, comment your thoughts below. New ideas are always appreciated! Feel free to connect with me on Twitter. Until then, goodbye!</p>
<h3 id="heading-helpful-resources">Helpful resources</h3>
<ul>
<li><p><a target="_blank" href="https://workat.tech/machine-coding/practice/design-parking-lot-qm6hwq4wkhp8">workat.tech</a> has abundant resources on cracking interviews at top product-based companies. This post is inspired by one such resource.</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/the-java-handbook/">Here's a Java handbook for beginners</a> that'll teach you a lot of foundational concepts.</p>
</li>
<li><p>And <a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-programming-in-java/">here's a more advanced Java handbook</a> that covers more advanced object-oriented programming concepts.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Deploy an Application to a Kubernetes Cluster ]]>
                </title>
                <description>
                    <![CDATA[ In today's ever-changing technology landscape, companies are looking for reliable and scalable ways to run and manage software. And containers have transformed the way we deliver software. Container orchestration platforms have made it possible to de... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deploy-docker-image-to-kubernetes/</link>
                <guid isPermaLink="false">66d8514be86088251dd27bc2</guid>
                
                    <category>
                        <![CDATA[ containers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kubernetes ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Tue, 22 Aug 2023 16:34:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/deploy-app-to-k8s-cluster.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In today's ever-changing technology landscape, companies are looking for reliable and scalable ways to run and manage software. And containers have transformed the way we deliver software.</p>
<p>Container orchestration platforms have made it possible to deploy and manage containerised applications. Kubernetes is one such platform that has been a game-changer for developers who are dealing with the challenges of application deployments.</p>
<p>Kubernetes has made it so much easier to manage and scale deployments according to your needs. In this tutorial, I am going to help you understand the simplicity of Kubernetes, so get ready.</p>
<p>We'll first take a Node application and package it using Docker. Then, I'll show you how to use Kubernetes – from setting up the cluster and creating deployments and services to scaling the application. Make sure you stay till the end to get the maximum value. It's going to be great.</p>
<p>You can find the full code <a target="_blank" href="https://github.com/KunalN25/sample-node-application">in this GitHub Repo</a>.</p>
<p>I'll start with a note on container orchestration.</p>
<h2 id="heading-container-orchestration">Container Orchestration</h2>
<p>Containers offer an efficient and isolated environment for your application. But as your application grows, so does the container count.</p>
<p>Juggling containers in production can quickly turn into a headache, especially if you are using microservices. Faster deployments, monitoring, scaling, networking, and load balancing suddenly become daunting tasks.</p>
<p>That's where container orchestration comes in. It automates these challenges and ensures that containers are operating smoothly. It simplifies the deployment and scaling processes, thus streamlining your workflow.</p>
<p>Adding to that, orchestration takes the stage in networking and facilitating communication between containers across multiple hosts. Want to expose your containers to the outside world? Orchestration makes it effortless.</p>
<h2 id="heading-how-to-prepare-a-packaged-application">How to Prepare a Packaged Application</h2>
<p>Your first task is to set up a Node application and package it into a Docker image. For this, you need to have Node.js installed in your system. If not, then follow <a target="_blank" href="https://radixweb.com/blog/installing-npm-and-nodejs-on-windows-and-mac">this</a> guide on installing Node on Mac and Windows.</p>
<p>You do not need to be familiar with either Node.js or JavaScript to go through this tutorial. Just follow the steps mentioned below. The main focus of this post is Kubernetes.</p>
<h3 id="heading-set-up-the-node-application">Set Up the Node Application</h3>
<p>To set up your Node app, create a folder called <code>sample-node-application</code> and navigate inside it. Run the command <code>npm init</code> and enter each field value accordingly with the entrypoint as <code>server.js</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-20-at-8.36.24-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>npm init command</em></p>
<p>A <code>package.json</code> file will be created that specifies the necessary dependencies your application needs. Create a file <code>server.js</code>, this will contain your APIs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./data.json"</span>)

<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.send(<span class="hljs-string">"Hello, Welcome to the Node App"</span>)
})

app.get(<span class="hljs-string">"/data"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.json(data)
})


app.listen(<span class="hljs-number">8000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"App is running"</span>)
});
</code></pre>
<p>Create a separate <code>data.json</code> file and add some mock data to it. You can generate mock data from <a target="_blank" href="https://www.mockaroo.com/">Mockaroo</a>.</p>
<p>Run the <code>node server</code> command to check if the app is running.</p>
<h3 id="heading-build-a-docker-image">Build a Docker Image</h3>
<p>Before building the image, check if you have Docker installed in your system. If not, then refer to the <a target="_blank" href="https://docs.docker.com/get-docker/">installation guides</a> for different operating systems. Run <code>docker --version</code> to confirm that Docker is installed.</p>
<p>This is how our Dockerfile will look:</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">FROM</span> node:<span class="hljs-number">18</span>-alpine

<span class="hljs-keyword">WORKDIR</span><span class="bash"> /sample-node-app</span>

<span class="hljs-keyword">COPY</span><span class="bash"> server.js /sample-node-app/</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package.json /sample-node-app/</span>
<span class="hljs-keyword">COPY</span><span class="bash"> data.json /sample-node-app/</span>

<span class="hljs-keyword">RUN</span><span class="bash"> npm install</span>

<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"node"</span>, <span class="hljs-string">"server"</span>]</span>
</code></pre>
<p>Run the following command to build the Docker image:</p>
<pre><code class="lang-python">docker build -t node-image .
</code></pre>
<p>Check if your image was created with the <code>docker images</code> command. Now, push this image to Docker Hub. Go to <a target="_blank" href="https://hub.docker.com/">Docker Hub</a> and sign in. If you do not have an account, then go ahead and register for one.</p>
<p>Once you are in, create a repository named node-image and make it public. Now, back to your terminal, run docker login and enter your username and password. Then, tag the image with your username.</p>
<pre><code class="lang-python">docker image tag react-example-image &lt;username&gt;/node-image
</code></pre>
<p>Push this image to Docker Hub with the following command:</p>
<pre><code class="lang-python">docker push &lt;username&gt;/node-image
</code></pre>
<p>Your image will be pushed to Docker Hub.</p>
<p>Here, I have explained the image creation steps briefly. If you want a more detailed explanation, then you can read my tutorial on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-dockerize-a-react-application/">How to Dockerize a React Application</a>.</p>
<p>Before diving into the next steps, let's first understand what Kubernetes is, why it is needed, and few key concepts.</p>
<h2 id="heading-what-is-kubernetes-and-why-do-you-need-it">What is Kubernetes and Why Do You Need It?</h2>
<p>Kubernetes (abbreviated as K8s) is an open-source container orchestration platform. Orchestration is all about automating deployments, scaling, and managing containers.</p>
<p>Kubernetes uses a declarative approach, where you define the desired state of your applications in a YAML file. Then, Kubernetes will work towards achieving that state and ensure that the state is maintained.</p>
<p>It enables close collaboration between development and operations teams, also helping enable efficient <a target="_blank" href="https://medium.com/gitconnected/what-is-devops-and-how-to-adopt-its-practices-6a4a7742bb65">DevOps</a> practices.</p>
<h3 id="heading-problems-that-kubernetes-helps-solve">Problems that Kubernetes Helps Solve</h3>
<p>Traditionally, multiple applications used to be deployed on physical servers. This presented a few problems.</p>
<p>If one application ends up taking more space than anticipated, then the other applications would not get enough resources. Also, scaling was difficult and expensive for organizations.</p>
<p>Then came VMs. They allowed better resource utilization than physical systems and also made scalability easier and cheaper. But containers provide a much more lightweight solution than VMs.</p>
<p>To run and manage these containers, we need Kubernetes to provide the necessary automation with the following features:</p>
<ul>
<li><p><strong>Service Discovery and Load Balancing</strong> allow applications to communicate with each other no matter where they are running.</p>
</li>
<li><p><strong>Automated Scaling</strong> enables Kubernetes to auto-scale the number of containers depending on the configurations provided.</p>
</li>
<li><p>With <strong>Self Healing,</strong> Kubernetes can restart any containers that stopped running or failed to run.</p>
</li>
<li><p>Kubernetes allows <strong>Mounting a Storage</strong> to your deployment automatically.</p>
</li>
<li><p><strong>Automated Rollouts:</strong> Kubernetes follows a declarative mechanism to achieve and maintain the desired state of the application.</p>
</li>
<li><p><strong>Secret and</strong> C<strong>onfig</strong> M<strong>anagement</strong>: You can add configs and secrets to deployments so your application can use whatever configuration it needs based on the environment it is deployed in (dev or prod).</p>
</li>
</ul>
<p>If you want to know more about Kubernetes and its components, visit the <a target="_blank" href="https://kubernetes.io/docs/concepts/overview/">docs</a>.</p>
<h2 id="heading-key-kubernetes-concepts">Key Kubernetes Concepts</h2>
<p>Following are the key concepts that you'll need to know to effectively use Kubernetes in your projcts.</p>
<h3 id="heading-what-are-pods">What are Pods?</h3>
<p>A pod is a single deployment unit in Kubernetes containing one or more containers. Pods are responsible for running your application's containers in the Kubernetes cluster. It is a single instance of a running application.</p>
<p>You can create a pod using simple YAML configuration. Usually, you do not need to create them explicitly. Instead, you can use the Deployment configuration to create a pod. We'll see how to do that shortly.</p>
<p>Even though a pod can run multiple containers, it is common practice to run a single container in a pod. Read more about pods <a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/pods/">here</a>.</p>
<h3 id="heading-how-do-deployments-work">How Do Deployments Work?</h3>
<p>Kubernetes aims to maintain the desired state of the application at all times. A Deployment describes the desired state through YAML configuration.</p>
<p>A deployment configuration is used to decide the number of replicas of your pods, modify the pod configuration, rollback to a previous state, scale up/down your application and more.</p>
<p>When you create a deployment, it will create the pods that run the containers you specified. Once you create a deployment configuration, you do not need to create a separate configuration file for pods. You'll understand more in the hands-on part.</p>
<p>Read more about deployments <a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">here</a>.</p>
<h3 id="heading-what-are-services">What are Services?</h3>
<p>Let's say you have multiple applications deployed as pods. These applications may need to communicate with each other. Each pod has its unique ip address, so they can simply use the same ip address to communicate, right? Actually, this presents a few problems.</p>
<p>Pods have a relatively shorter lifespan. If any issue comes up and the pod is terminated, Kubernetes springs up a new pod as it needs to maintain the desired state of the deployment.</p>
<p>This new pod would have a different IP address. But the other pods are still using the old pod's IP to communicate. So, this new pod would not be discoverable unless all other pods update the IP to which they are communicating.</p>
<p>This is where services come in. Services help expose groups of pods over a network by adding a layer of abstraction. This abstraction provides a stable endpoint for the pods to communicate with each other.</p>
<p>Read more about services <a target="_blank" href="https://kubernetes.io/docs/concepts/services-networking/service/">here</a>.</p>
<p>Let's look at one last concept, the Kubernetes Cluster. I know it feels like a lot of theory, but don't worry, the hands-on part is coming.</p>
<h3 id="heading-the-kubernetes-cluster">The Kubernetes Cluster</h3>
<p>A K8s cluster is a group of machines (or nodes) that run and manage your applications. The cluster consists of worker nodes and a control plane that controls and manages these workers.</p>
<p>The control plane makes several decisions like scheduling, starting up a new pod, etc. It consists of the following components:</p>
<ul>
<li><p><strong>api-server</strong>: Exposes the Kubernetes API</p>
</li>
<li><p><strong>etcd</strong>: Key-value store for cluster data</p>
</li>
<li><p><strong>scheduler</strong>: Watches for newly created pods and assigns a worker node to run them.</p>
</li>
<li><p><strong>controller-manager</strong>: Runs a control loop that watches the state of the cluster through the api-server and if necessary, moves the current state to the desired state.</p>
</li>
</ul>
<p>Worker Nodes are responsible for running and maintaining the pods. Each worker node consists of the following components:</p>
<ul>
<li><p><strong>kubelet</strong>: Makes sure the containers are healthy and running in the Pod.</p>
</li>
<li><p><strong>kube-proxy</strong>: Network proxy that runs on each node and allows communication with the worker node from inside and outside the cluster.</p>
</li>
<li><p><strong>container-runtime</strong>: Responsible for running containers</p>
</li>
</ul>
<p>That's it for the main concepts – let's dive into the hands-on part.</p>
<h2 id="heading-how-to-deploy-to-a-kubernetes-cluster">How to Deploy to a Kubernetes Cluster</h2>
<p>So far, we have created a Docker image of the Node application and pushed it to the Docker Hub. The image can be accessed from anywhere.</p>
<p>How let's see how you can take this application and run it in a Kubernetes Cluster.</p>
<h3 id="heading-installation">Installation</h3>
<p>Let's install the Kubernetes command line utility, <em>kubectl</em>. You will find the guides for installation on Linux, Mac and Windows <a target="_blank" href="https://kubernetes.io/docs/tasks/tools/#kubectl">here</a>.</p>
<p>After following the steps mentioned, run the following command to check if <em>kubectl</em> was installed:</p>
<pre><code class="lang-bash">kubectl version --client
</code></pre>
<h3 id="heading-set-up-the-kubernetes-cluster">Set Up the Kubernetes Cluster</h3>
<p>To deploy your application, you need to set up a Kubernetes Cluster that will run your pods and services. There are lot of clusters provided by multiple cloud providers like Google, Amazon and Microsoft. For this application, we will use Minikube.</p>
<p>Minikube is a tool that lets your run a single-node K8s cluster on your computer. It is a personal playground for trying out Kubernetes in your system.</p>
<p>Refer to <a target="_blank" href="https://minikube.sigs.k8s.io/docs/start/">this</a> guide for setting up minikube on Mac or Windows. Check if Minikube was installed by running the <code>minikube version</code> command.</p>
<p>Run the <code>minikube start</code> command to start a local Kubernetes cluster.</p>
<h3 id="heading-write-the-yaml-configurations">Write the YAML Configurations</h3>
<p>Now, let's write our deployment and service configurations in YAML files.</p>
<p>First, let's see how to create the deployment config, step by step.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">sample-node-app</span>
  <span class="hljs-attr">namespace:</span> <span class="hljs-string">default</span>
</code></pre>
<ul>
<li><p><code>apiVersion</code>: Specifies the API version of the resource,</p>
</li>
<li><p><code>kind</code>: Defines the type of resource, which is a Deployment.</p>
</li>
<li><p><code>metadata</code>: Contains metadata about the deployment. Here, we have specified the name of the deployment and set the namespace to default.</p>
</li>
</ul>
<pre><code class="lang-yaml"><span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">2</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">sample-node-app</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">sample-node-app</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">sample-node-app</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">kunalmac25/node-image</span>
        <span class="hljs-attr">imagePullPolicy:</span> <span class="hljs-string">Always</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">8000</span>
</code></pre>
<ul>
<li><p><code>spec</code>: Describes the desired state of the deployment.</p>
</li>
<li><p><code>replicas</code>: Specifies the desired number of replicas (instances) of the application to run, which is 1 in this case.</p>
</li>
<li><p>The <code>selector</code> and <code>matchLabels</code> fields specify labels that the deployment can identify the pods with.</p>
</li>
<li><p><code>template</code>: Defines a template for your pod. You can specify some metadata under the field <code>metadata</code>. Mention the label with which the pod should be identified.</p>
</li>
<li><p><code>spec</code> field under <code>template</code> describes the desired state of the pod, including the list of containers.</p>
</li>
<li><p>For each container, you can specify the name, the image it should pull from, and the port to which it is exposed. <code>imagePullPolicy</code> specifies the <a target="_blank" href="https://kubernetes.io/docs/concepts/containers/images/#image-pull-policy">image pull policy</a>. Here, I have used <code>Always</code> (always pull the latest image from the registry).</p>
</li>
</ul>
<p>These are the contents of the <code>deployment.yaml</code> file. Now, let's write our <code>service.yaml</code>.</p>
<pre><code class="lang-python">apiVersion: v1
kind: Service
metadata:
  name: node-service
  namespace: default
</code></pre>
<p>Similar to the deployment, start with the API version and some metadata about the service.</p>
<pre><code class="lang-python">spec:
  type: LoadBalancer
  selector:
    app: sample-node-app
  ports:
    - port: <span class="hljs-number">80</span> 
      targetPort: <span class="hljs-number">8000</span>
</code></pre>
<ul>
<li><p>Here, <code>spec</code> field describes the desired state of the Service which is of type <code>LoadBalancer</code>.</p>
</li>
<li><p><code>selector</code>: Specifies the label that identifies with the pod the service should direct traffic to.</p>
</li>
<li><p><code>ports</code>: Specifies the list of ports that the service should expose.</p>
</li>
<li><p><code>port</code>: Specifies the port that the service listens on. External traffic will come to this port, while the <code>targetPort</code> specifies the port on the pods that the service should forward traffic to. In our case, the incoming traffic on the service's port 80 will be sent to the pods on port 8000.</p>
</li>
</ul>
<h3 id="heading-create-the-pod-deployment-and-service">Create the Pod, Deployment, and Service</h3>
<p>Use <code>kubectl apply</code> to apply the above configurations and create the pods, deployment, and service.</p>
<pre><code class="lang-bash">kubectl apply -f deployment.yaml
</code></pre>
<pre><code class="lang-bash">kubectl apply -f service.yaml
</code></pre>
<p>Alternatively, you can also put both these configs in a single <code>manifest.yaml</code> file and run the apply command just once.</p>
<pre><code class="lang-bash">kubectl apply -f manifest.yaml
</code></pre>
<p>Check your pods, deployments, and services using the <code>kubectl get</code> commands.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-16-at-4.25.04-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Pods, Deployments, and Services</em></p>
<p>Make sure you have executed the <code>minikube start</code> command before applying any files, as you need to start a cluster to run your pods.</p>
<p>You can see from the above output that both the replicas of the pod are running fine. If it shows 0/2 under READY, that means there was some issue while creating the container. You should check if your application is working properly before deploying again.</p>
<p>You can also check the pod logs with the <code>kubectl logs</code> command.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-16-at-4.27.47-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Pod logs</em></p>
<p>Minikube also provides a dashboard that shows all your pods, deployments, and services as a web UI. Run the <code>minikube dashboard</code> command and your browser will spring up the dashboard.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-16-at-4.29.20-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Minikube Dashboard</em></p>
<h3 id="heading-access-your-application">Access Your Application</h3>
<p>To access your service in the Minikube cluster, run the following command to get the endpoint at which your LoadBalancer service is exposed:</p>
<pre><code class="lang-bash">minikube service &lt;service-name&gt; --url
</code></pre>
<p>Open the same endpoint in a browser or access it via Postman.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-19-at-6.37.11-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Endpoint Accessible on the Browser</em></p>
<p>You can also use localhost instead of the IP address, as they are the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-19-at-6.38.43-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>API Accessible via Postman</em></p>
<h3 id="heading-scaling-your-application">Scaling Your Application</h3>
<p>Your application is up and running. With increasing demand, you may need to scale up your application to ensure optimal performance.</p>
<p>To scale up your application, increase the number of replicas of your deployment by running the following command:</p>
<pre><code class="lang-python">kubectl scale deployment &lt;deployment-name&gt; --replicas=&lt;desired-number&gt;
</code></pre>
<p>Specify the desired number of replicas and it will scale up your pods.</p>
<pre><code class="lang-bash">kubectl scale deployment sample-node-app --replicas=4
</code></pre>
<p>After running the above command, run <code>kubectl get deployments</code> to see that the number of replicas has gone up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot-2023-08-19-at-6.48.55-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Increased Number of Replicas</em></p>
<p>Alternatively, you can modify the Deployment YAML file by changing the number of replicas and running the <code>kubectl apply</code> command again.</p>
<p>If you no longer need a large number of pods and want to scale down your application, just run the same command and specify a smaller number of replicas.</p>
<pre><code class="lang-python">kubectl scale deployment sample-node-app --replicas=<span class="hljs-number">2</span>
</code></pre>
<h2 id="heading-a-word-about-cloud-providers">A Word About Cloud Providers</h2>
<p>So far you have created a Docker image and deployed it into a local Kubernetes cluster. We used Minikube for this purpose. But if you want to distribute your application to the outside world, you need to use cloud providers.</p>
<p>There are many options available such as AWS, Azure, GCP, VMware Tanzu, and others. These platforms provide a lot of services like Cluster Management, Scaling, Networking and Storage, CI/CD Integration, and so on.</p>
<p>These platforms combine the capabilities of Kubernetes with the strengths of their own cloud systems. Each product comes with its own services and pricing plans, so choose whichever one fits in with your requirements and budget.</p>
<p>In a rapidly evolving cloud landscape, it is important to understand what each cloud provider offers and make informed decisions that align with your organisations requirements and goals.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Kubernetes is a popular container orchestration platform and is very easy to use. Having a strong grasp on its concepts helps you leverage this platform for your application.</p>
<p>In this tutorial, my objective was to provide a comprehensive, step by step guide on deploying your application to a Kubernetes cluster. I also set out to establish a foundation on some key concepts of Kubernetes that include pods, deployments, services and the cluster itself.</p>
<p>I started with a simple Node app and packaged it into a Docker image. Once you were clear with the key concepts, I gave detailed steps right from installation and setting up the Kubernetes cluster to deploying your application as pods and exposing them through services.</p>
<p>Kubernetes is slowly taking over the cloud landscape and it is here to stay. I hope I was able to make Kubernetes easy for you. This will surely help you deploy your applications to any Kubernetes cluster, not just the ones I mentioned.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Dockerize a React Application – A Step by Step Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ Picture this: you have developed an application that is ready to be deployed. You have worked really hard on it, so you want to make sure it gets deployed seamlessly and the final product is both fast and reliable. Enter images and containers. Images... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-dockerize-a-react-application/</link>
                <guid isPermaLink="false">66d8514f39c4dccc43d4d4bd</guid>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jul 2023 14:54:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/pexels-pixabay-39656--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Picture this: you have developed an application that is ready to be deployed. You have worked really hard on it, so you want to make sure it gets deployed seamlessly and the final product is both fast and reliable. Enter images and containers.</p>
<p>Images and containers help you package your application and run it in a lightweight and isolated environment. Containers make it possible to make faster and scalable deployments. And it's not that hard to start using them. All you have to do is write some scripts and run a few commands to have a container up and running. How cool is that?</p>
<p>In this tutorial, I am going to take a React application and show you, step by step, how to build an image, push it to a remote registry, and use that image to run your application in a container.</p>
<p>To follow along with this tutorial, I am assuming you are already familiar with the basics of images and containers. I'll start by explaining what Docker is and then dive into the process.</p>
<h2 id="heading-what-is-docker">What is Docker?</h2>
<p>Docker is an open-source platform developer by <a target="_blank" href="https://www.docker.com/company/">Docker, Inc.</a> It enables you to package your application and its dependencies and run it all in an isolated environment, called the container. With just a small set of instructions, you can easily build images and run them as containers.</p>
<p>Docker containers are extremely lightweight and efficient. Due to isolation, each container runs differently and the container processes do not interfere with each other. Docker also has its own version control system, Docker Hub, which we'll discuss later on in the tutorial.</p>
<p>Docker is widely used by enterprise technologies and cloud services that have chosen to adopt containerization for faster deployments. Lastly, Docker has a vast community and an ever-expanding ecosystem of tools and services. For more info, you can go through the <a target="_blank" href="https://docs.docker.com/get-started/">docs</a>.</p>
<p>Okay, enough about Docker (actually, not). You are here to get some hands-on practice and that's what we'll do here. Before we get started, you first need to install Docker on your system. Refer to <a target="_blank" href="https://docs.docker.com/get-docker/">this</a> for a guide on installing Docker on different operating systems.</p>
<p>Run the command <code>docker --version</code> to check if Docker is installed.</p>
<h2 id="heading-how-to-create-a-simple-react-application">How to Create a Simple React Application</h2>
<p>Use the following command to set up a simple React application.</p>
<pre><code class="lang-bash">create-react-app react-docker-example
</code></pre>
<p>You do not need to add any more dependencies to the project. All you need is a working application. Run <code>npm start</code> to see if the app is running properly.</p>
<p>Once the application is running and ready to deploy, we are ready to start Dockerizing it!</p>
<h2 id="heading-how-to-write-a-dockerfile">How to Write a Dockerfile</h2>
<p>To build an image of your application, you need to specify instructions for the same in a Dockerfile. The instructions from this file will be executed one after the other. You'll find a reference to all the instructions <a target="_blank" href="https://docs.docker.com/engine/reference/builder/">here</a>.</p>
<p>A Docker image consists of different layers stacked on top of each other. Each instruction in the Dockerfile adds a new layer on top of the existing ones. Each layer in the image is stored as a SHA-256 hash.</p>
<p>Note that not all instructions create new layers. Certain instructions like <code>LABEL</code>, <code>ENV</code>, and <code>ARG</code> are only set to provide some metadata for the image. Read <a target="_blank" href="https://kodekloud.com/blog/docker-image-layers/">this</a> to learn more about image layers.</p>
<p>Let's go over the instructions we'll need, one by one.</p>
<pre><code class="lang-python">FROM node:<span class="hljs-number">18</span>-alpine
</code></pre>
<p>This instruction pushes the base image from a remote repository (in this case, the Docker Hub) and defines the starting point for the image layers. The syntax for specifying the image is</p>
<p><img src="undefined" alt="undefined" width="600" height="400" loading="lazy"></p>
<p>: where tag represents the version of the image.</p>
<p>Since React is a Node-based application, we'll pull a Node image from the repository. Specify the version of the image you want to pull. You can get a list of versions <a target="_blank" href="https://hub.docker.com/_/node/tags">here</a>.</p>
<p>If you specify <em>latest,</em> it will pull the latest version – that is whenever the image is upgraded, it will always fetch the latest one. But this is not a good practice for applications deployed in production.</p>
<pre><code class="lang-python">WORKDIR /react-docker-example/
</code></pre>
<p>This command sets the working directory for any commands you add in the Dockerfile. So, while building the image, the commands will be executed in this directory.</p>
<pre><code class="lang-python">COPY public/ /react-docker-example/public
COPY src/ /react-docker-example/src
COPY package.json /react-docker-example/
</code></pre>
<p>These instructions will copy the files we need into the working directory. We only need the public and src folders (where your code resides), and the package.json file to run the application.</p>
<pre><code class="lang-python">RUN npm install
</code></pre>
<p>The <code>RUN</code> instruction executes any command by adding a new layer on top of the current ones, thus modifying the image. This modified image will be used for the next steps.</p>
<p>In this case, it installs all the dependencies specified in the <code>package.json</code> file. This is why we did not copy the <code>node_modules</code> folder into the working directory. The folder will be created after this command gets executed.</p>
<pre><code class="lang-python">CMD [<span class="hljs-string">"npm"</span>, <span class="hljs-string">"start"</span>]
</code></pre>
<p>This instruction defines the command that will be executed when starting a container from the image. There can only be one <code>CMD</code> instruction in the Dockerfile. If there are more than one, then only the last one will be considered.</p>
<p>Since <code>npm start</code> is the command used for starting a React app, we'll specify the same for running the container.</p>
<h2 id="heading-how-to-build-the-image">How to Build the Image</h2>
<p>Now that we have written the Dockerfile, it's time to build the image. Open your terminal (or cmd in Windows) and execute the following command.</p>
<pre><code class="lang-python">docker image build -t &lt;image_name&gt;:&lt;tag&gt; &lt;path&gt;
</code></pre>
<p><code>-t</code> option specifies the name and tag for the image. <code>&lt;path&gt;</code> represents the path in which you want to run the command.</p>
<p>We'll name the image react-docker-example and give it a tag <code>latest</code>. Make sure you change into the project's root directory using <code>cd react-docker-example</code> before executing the command.</p>
<pre><code class="lang-python">docker image build -t react-example-image:latest .
</code></pre>
<p>The <code>.</code> at the end represents the current directory.</p>
<p>Once you hit enter, this command will execute each instruction in the Dockerfile one by one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-6.08.46-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output of the docker build command</em></p>
<p>In the above image, you can see that each instruction in the Dockerfile is getting executed in a new layer on top of the previous ones. In the end, the image is represented by a single sha256 hash which is the image id.</p>
<p>Now, run <code>docker images</code> to see a list of images in your system. You'll see the details of the image you just created.</p>
<p>That's all it takes to build a Docker image: a few instructions in a Dockerfile and one command.</p>
<h2 id="heading-how-to-push-the-image-to-docker-hub">How to Push the Image to Docker Hub</h2>
<p>Now, the image that you created resides in your local system. But what if you want to make it accessible to your team members? Similar to Git, you would need to push the image to a remote repository.</p>
<p>Docker Hub is a repository (or registry) where you can push your image as well as access other open source images. Similar to Node, there are other base images such as Ubuntu, Python, Redis, and so on. Check them out <a target="_blank" href="https://hub.docker.com/search">here</a>.</p>
<p>To start using <a target="_blank" href="https://hub.docker.com/signup">Docker Hub</a>, you first need to create an account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-9.26.02-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Register into Docker Hub</em></p>
<p>Then, go to repositories and click on Create repository.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-9.25.24-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Repositories</em></p>
<p>Specify a repository name and mark it public or private. In the community edition, you are only allowed to have 1 private repository. Click on Create.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-9.37.41-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Create Repository</em></p>
<p>Now, this is how your repository looks. You can push your image into this repository. Since this is a public repository, anyone can pull your images. But only you have the permission to push.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-9.39.30-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now that you have created your remote repository, it's time to push your image. First, you need to login using your credentials.</p>
<pre><code class="lang-python">docker login
</code></pre>
<p>After this, tag the image with your username.</p>
<pre><code class="lang-python">docker image tag react-example-image &lt;username&gt;/react-example-image
</code></pre>
<p>Now, run this command to push the image.</p>
<pre><code class="lang-python">docker push kunalmac25/react-example-image
</code></pre>
<p>Since you have not specified an image tag (that is, a version), it will use the default one – the latest. Unlike the version tag, it is necessary to tag the image name with your username. This gives you the complete ownership of the image and prevents any potential naming conflicts.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-9.49.48-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image pushed to the repository</em></p>
<p>The latest version of your image has been pushed into the repository. Let's say, in the future, you have made changes to your application. You can create an upgraded version of the same image, tag it with the new version name and then, push it.</p>
<pre><code class="lang-python">docker image build -t react-example-image:upgrade .
</code></pre>
<pre><code class="lang-python">docker image tag react-example-image:upgrade &lt;username&gt;/react-example-image:upgrade
</code></pre>
<pre><code class="lang-python">docker push kunalmac25/react-example-image:upgrade
</code></pre>
<p>Now, open your repository and check the images.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-13-at-10.58.50-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>List of Images</em></p>
<p>You can see a list of all versions of your images.</p>
<h2 id="heading-how-to-create-a-container-from-the-image">How to Create a Container from the Image</h2>
<p>At this point, we have bundled package including everything needed to run the React application. Now, we need to create a container to run your application. Run the following command.</p>
<pre><code class="lang-python">docker run -dp <span class="hljs-number">8000</span>:<span class="hljs-number">3000</span> --name react-example-container react-docker-example:latest
</code></pre>
<ul>
<li><p><code>-d</code> runs the container in detached mode – that is, it will run in the background and not display the running process on your terminal.</p>
</li>
<li><p><code>-p</code> maps the port in the form <code>&lt;host_port&gt;:&lt;container_port&gt;</code>. The host port represents the port on the host machine that is mapped to the port inside the container. Since a React app is exposed through port 3000, we will map it to the port 8000 on your host machine.</p>
</li>
<li><p>The <code>--name</code> flag specifies the name for the container.</p>
</li>
<li><p>After these, you specify the image name and tag.</p>
</li>
</ul>
<p>If the image does not exist on your local system, it will try to find the image in the Docker registry.</p>
<p>To check this, delete your local image using <code>docker image rm react-example-image</code> and run the above command. Since there is an image with the same name on Docker Hub (the one you just pushed), it will download the image and create a container out of it.</p>
<p>Now, run <code>docker ps</code> or <code>docker container ps</code> to show a list of all the running containers.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-14-at-9.14.41-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Running Containers</em></p>
<p>Now, open your browser and go to <code>http://localhost:8000</code>. You'll be able to access your application.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-15-at-8.27.46-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Application Running in a Container</em></p>
<p>To stop a running container, use the <code>docker stop</code> command with the container id or name.</p>
<pre><code class="lang-python">docker stop &lt;container_id&gt;
</code></pre>
<p>Now, if you run <code>docker ps</code>, it won't show the container as it only shows the running ones. If you want to see all the containers, including the non-running ones, use <code>docker ps -a</code>.</p>
<p>Also, navigate to the same URL and you won't be able to see anything since the container is not running. To restart the container, run <code>docker start &lt;container_id&gt;</code>.</p>
<p>To remove the container, use the <code>docker rm</code> command followed by the container id or name.</p>
<pre><code class="lang-python">docker rm &lt;container_id&gt;
</code></pre>
<p>Congratulations! You have just run the application in an isolated environment where no other process is going to interfere with it. This makes your application faster and more reliable. Containers are extremely lightweight, so you can easily scale up the application.</p>
<p>Also, you do not need to worry about missing dependencies or conflicting versions. All the dependencies that your application needs are bundled inside the container. That's the beauty of containers!</p>
<h2 id="heading-next-steps">Next Steps</h2>
<p><img src="https://images.unsplash.com/photo-1505909487039-08022c92a8ab?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEzfHxuZXh0JTIwc3RlcHN8ZW58MHx8fHwxNjg5NTgxMTUyfDA&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Image" width="2000" height="1331" loading="lazy"></p>
<p><em>Photo by [Unsplash](https://unsplash.com/@createandbloom?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Photo Boards / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit)</em></p>
<p>At this point, you have a packaged application running in its own isolated environment. But we are just halfway there. The container is still running on your local machine. Once your application is tested and ready to go, you'll need to ship that container.</p>
<p>There are several orchestration platforms like Kubernetes and Docker Swarm and cloud provides like Google, AWS, Azure, and others that make it possible. These are very useful when you want to deploy your application in different environments (dev, test, or production). We'll discuss container orchestration in a future post. That's it for today.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, I explained what Docker is and why you should use it. Then, I showed you how to build an image by writing a Dockerfile, which is just a set of instructions to build a Docker image. After building an image in your local system, you can push that image to a remote registry, Docker Hub.</p>
<p>Once your application is all packaged up, it is time to run the application in a container, an isolated environment with everything that your application needs. You can start, stop and remove the containers using Docker commands. After that, I showed you a glimpse of what you could do next.</p>
<p>Containers provide a very lightweight and a faster solution for all your deployments and Docker makes it very easy and convenient. Containers have a really promising future with more and more enterprises adopting containerization.</p>
<p>I have explained all the steps in simple words and a straightforward example. I hope you were able to get a good grasp of the process.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, Goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
