<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Afan Khan</title>
    <description>The latest articles on DEV Community by Afan Khan (@whyafan).</description>
    <link>https://dev.to/whyafan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1024322%2F0e08e287-53d0-4873-94e0-90685d1acbbe.png</url>
      <title>DEV Community: Afan Khan</title>
      <link>https://dev.to/whyafan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/whyafan"/>
    <language>en</language>
    <item>
      <title>Microsoft is ditching React</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Wed, 12 Jun 2024 08:24:40 +0000</pubDate>
      <link>https://dev.to/whyafan/microsoft-is-ditching-react-5h98</link>
      <guid>https://dev.to/whyafan/microsoft-is-ditching-react-5h98</guid>
      <description>&lt;p&gt;Recently, the Microsoft Edge Team wrote an article on how Microsoft is improving Edge to become faster. However, Microsoft took shots at React and announced they are not going to use it for Edge anymore.&lt;/p&gt;

&lt;p&gt;After their article, developers questioned whether React is worth learning anymore.&lt;/p&gt;

&lt;p&gt;I will explain their entire article and how it affects React, JavaScript Developers, and what are the true intentions of the Microsoft Edge Team.&lt;/p&gt;

&lt;h2&gt;
  
  
  History
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Microsoft Edge is built using Chromium&lt;/em&gt;, an Open-Source web browser project by Google. The default UI of Microsoft Edge is derived from Chromium.&lt;/p&gt;

&lt;p&gt;Microsoft doesn't want Edge to look like Chrome (obviously). Therefore, Edge has UI components and elements designed by Microsoft. However, these components are made using React.&lt;/p&gt;

&lt;p&gt;Many small components throughout Edge are created using React which collectively builds the entire browser.&lt;/p&gt;

&lt;p&gt;The entire Edge browser isn't a React application. It combines multiple components in the form of HTML pages with React in them. The menu, dropdown, and the favourites tab are mini React apps.&lt;/p&gt;

&lt;p&gt;That's not efficient, right? Especially for UI data that never changes dynamically. &lt;strong&gt;Its inefficiency has caused Microsoft to doubt React&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;But this story is half-baked&lt;/em&gt;. We'll soon unveil whether React was at fault or Microsoft had a manufactured flaw.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Prepping for an interview? Leetcode is key. I built a Notion Dashboard to help you ace those DSA rounds. Store solutions, track progress, log problems — all in one place for $10.&lt;/p&gt;

&lt;p&gt;Plus, get bonus resources for TypeScript, Python, and JavaScript, free lifetime access to a $4.99 exclusive community, and 25% off upcoming products. Grab it now and ace your prep!&lt;/p&gt;
&lt;/blockquote&gt;


&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://store.afankhan.com/l/codenexus" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fv1te5q3tv0gi3fypqbunptdhaiti" height="auto" class="m-0"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://store.afankhan.com/l/codenexus" rel="noopener noreferrer" class="c-link"&gt;
          CodeNexus - Crack Your Dream Tech Job Interview
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          Picture yourself dominating your coding interview, smoothly walking the interviewer through your solutions because you've meticulously organized everything. It's a win for you, but it's not easy without this dashboard. Here's how you can win easily.How will this Dashboard help you? 💵Ace your coding interviews and land your dream job. You cannot afford to make mistakes.Prepare for your coding interviews faster and focus on the bigger picture.Outpace other candidates. Many neglect the power of logging and organizing.Get closer to becoming an organised and experienced engineer.Spend less time memorizing and more time-solving questions and sharpening your skills.Log your progress to iterate and improve. Help others by sharing your logged solutions.Identify your weak spots and focus on them.Let me break it down for you. Data Structures and Algorithms are one of the most crucial parts of an interview. No DSA? Don't bother showing up to interviews.It's not about memorizing LeetCode or HackerRank solutions. It's about problem-solving skills that land you that dream job.What's it really about? 🧩DSA tests your ability to think on your feet. Recruiters want to see how you think under pressure, how you solve problems, and your logical approach.It shows how you break down complex problems. Success in Coding Interviews comes from explaining your thought process.But here's the kicker: Solving hundreds of questions doesn't mean anything if you blank out in interviews. Solution? Treat interviews like practice. Organize your work. Tag solutions. Build a database. And that's exactly what my template is all about.Unorganized notes = failure. Period. Practice smart, not just hard. What's Included? 👨‍🏫Log solutions, approaches, problems, constraints, examples, and complexitiesOrganize by difficulty or languageTag with topics for easy filteringAccess your personal solution library anytimeInvesting in this dashboard is minimal compared to the value of becoming a proficient engineer.Bonus 🎁CodeNexus isn't just about questions and solutions. It's packed with resources to level up your JavaScript, Python, or TypeScript game. I've handpicked the best Udemy courses, podcasts, and must-read books, all vetted by top developers.You'll get free access to my exclusive Discord community and other perks worth $4.99 a month. Upgrade to the pro version and you'll get all the bonus gifts, including lifetime access to the membership. This deal saves you over $50.Snag CodeNexus now and get a sweet 25% discount (up to $7) on my upcoming eBook. It's all there waiting for you inside the template.Afan Khan LLC - 502 W 7th St, STE 100, Erie, Pennsylvania, USA.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fhd88vtri1kk5bpacr6ecjgr6uxd2"&gt;
        store.afankhan.com
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;





&lt;h2&gt;
  
  
  The Problems
&lt;/h2&gt;

&lt;p&gt;Microsoft claims that React isn’t efficient, so they made improvements and announced it in an article published on &lt;em&gt;May 28th, 2024&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/avJmgfGpoJA"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Microsoft observed that the bundles of code shared between multiple components were too large and that caused the browser to slow down.&lt;/p&gt;

&lt;p&gt;They weren’t supposed to share a bundle with different components, but as they claim it is a problem, here are their reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;There was a modularity issue with the UI code. &lt;strong&gt;The teams working on different components shared common bundles, files, etc&lt;/strong&gt;. It resulted in one part of the UI slowing down another part by sharing things that weren’t necessary.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Microsoft used a framework that relied on JavaScript to render the UI using the client-side rendering technique&lt;/em&gt;&lt;/strong&gt;. Microsoft claims this is the second reason to slow their browser down.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As I explained earlier, Edge shared multiple React applications.&lt;/p&gt;

&lt;p&gt;They didn’t initiate multiple React projects but used a single JavaScript Bundle in various places and mounted the Bundle to multiple props in many components.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A JavaScript Bundle is an optimization technique that combines multiple JavaScript files into a single line to reduce and process the server requests efficiently.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And the second reason is why I am writing this article. Indirectly, Microsoft addressed React as the framework that caused the bundle problem for them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w08s3e7d9tgm0xa3tea.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w08s3e7d9tgm0xa3tea.png" alt="WIndows + MacOS Image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Microsoft addressed React indirectly because they are working on React-based projects, like React Native for Windows, MacOS, and Xbox. However, they still loathe it for Edge.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Even though Microsoft is building React Native, they still don’t use it for Edge&lt;/strong&gt;. Edge is a native desktop application and React Native would be an ideal solution, but Microsoft begs to differ.&lt;/p&gt;

&lt;p&gt;It is because using HTML, CSS, and JavaScript, or React for menus, dropdowns, etc., is a common pattern or technique, or it was in the olden days. There’s a reason why they are switching, right?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Few01yhzkd8mrp56kpemb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Few01yhzkd8mrp56kpemb.png" alt="Wii Settings Page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the ancient days, Menus and their options were individual HTML files. Every button or link to perform a specific action would redirect to an HTML file.&lt;/p&gt;

&lt;p&gt;However, that old pattern was only used for components like a Menu. But Microsoft clearly didn’t understand that.&lt;/p&gt;

&lt;p&gt;They used an HTML file with React for every simple component. Every HTML file required JavaScript. And they shared this JavaScript code with every team as bundles of code.&lt;/p&gt;

&lt;p&gt;Microsoft embedded multiple HTML pages (in React apps) into their browser to control their entire UI. And now, they are looking for a solution to both problems.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;If you’re gearing up for an interview, I’ve got you covered. I’ve put together a killer list of must-know 102 JavaScript topics, 200+ JavaScript Interview questions, and 102 resources to learn them in a Notion Template. Grab it for just $5. Don’t miss out.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://store.afankhan.com/l/200-JS-Questions-Concepts-Resources" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fj2cghzx9lqcieo2nvld5k2ejr1yd" height="auto" class="m-0"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://store.afankhan.com/l/200-JS-Questions-Concepts-Resources" rel="noopener noreferrer" class="c-link"&gt;
          200+ Key JavaScript Interview Questions &amp;amp; Topics
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          Finally, a one-stop collection of key interview questions and concepts, each paired with resources.207 JavaScript Interview Questions.102 Unique Concepts Asked in JavaScript Interviews.102 Resources from across the Internet to help you learn.😵 Understanding the ProblemWhat’s the most valuable asset for someone prepping for an interview? Time. If you can't manage your time right, you won't get through everything. And if that happens, your dream job? Gone with the wind.It's about the effort too. Why spend an entire day digging through fifteen websites for interview questions, only to find they're all repetitive? Each site has the same questions, just jumbled up. It's a waste of time and effort.What’s more important? Your dream job. You can't bet $29 against $300,000+, right?🧰 Presenting the SolutionI’ve put together a list of questions, concepts, and resources based on their difficulty to help you prep for your JavaScript interview. These are hand-picked from around the globe with real recruiting experience.🎁 BonusAnd as a bonus, snag this list now and get a sweet 25% discount on my upcoming eBook. It's all there waiting for you inside the Notion list.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fhd88vtri1kk5bpacr6ecjgr6uxd2"&gt;
        store.afankhan.com
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;





&lt;h2&gt;
  
  
  The Solution
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;For starters, React wasn’t the problem&lt;/strong&gt;. Microsoft implemented it incorrectly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6srynnm925c72tbtwl8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6srynnm925c72tbtwl8.png" alt="Youtube Comment"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A bundle should work for a specific webpage and serve its purpose independently. Each page could have an individual bundle or collection.&lt;/p&gt;

&lt;p&gt;However, when you share the same bundle or files across the work of different teams, you must expect chaos. Every team accesses and modifies the same bundles.&lt;/p&gt;

&lt;p&gt;The outcome was expected. React wasn’t meant for what they were doing with it. React isn’t slow. But you cannot expect it to be blazing fast when you create dozens of instances.&lt;/p&gt;

&lt;p&gt;Microsoft came up with a solution to a problem they created. They created a custom framework.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs9rkjkug9ibcsdfb4u0k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs9rkjkug9ibcsdfb4u0k.png" alt="Microsoft Image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Microsoft announced WebUI 2.0 (not Web 2.0). A markup-first architecture. It solves the problem of large code bundles by minimizing their size and the amount of JavaScript that runs during the initialization path.&lt;/p&gt;

&lt;p&gt;Microsoft has started using this new architecture to solve both problems I stated earlier. They used React for the wrong purpose, forgot that React Native exists, and solved a manufactured problem.&lt;/p&gt;

&lt;p&gt;First, they used individual HTML files for each component with React inside them. Then, they offloaded the JavaScript code required by each HTML file into one bundle shared by ten other teams.&lt;/p&gt;

&lt;p&gt;And now, they don’t use React anymore. What do you think about this?&lt;/p&gt;




&lt;p&gt;If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="mailto:director@afankhan.com"&gt;director@afankhan.com&lt;/a&gt; (Afan Khan LLC). Otherwise, Twitter (X) is the easiest way to reach out — &lt;a href="https://x.com/whyafan" rel="noopener noreferrer"&gt;@whyafan&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>news</category>
    </item>
    <item>
      <title>How to use NextAuth.JS with Discord</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Mon, 13 May 2024 07:32:33 +0000</pubDate>
      <link>https://dev.to/whyafan/how-to-use-nextauthjs-with-discord-6le</link>
      <guid>https://dev.to/whyafan/how-to-use-nextauthjs-with-discord-6le</guid>
      <description>&lt;p&gt;I was working on a dashboard project recently and had the task of letting Discord users log in to the application and choose one of their servers to modify its properties.&lt;/p&gt;

&lt;p&gt;For someone who hadn't implemented authentication with NextJS before, I was clueless. I kept switching between NextAuth, Auth0, Clerk, and Supabase. I abandoned NextAuth in the first few seconds when I experienced an error. &lt;/p&gt;

&lt;p&gt;Being a newbie is difficult. More often than not, these first options are the most ideal. I tried everything and came back to NextAuth. I figured out how to implement it and spent countless hours, so you don't have to!&lt;/p&gt;

&lt;p&gt;Let's dive into the article and see how to implement authentication ourselves.&lt;/p&gt;

&lt;h2&gt;
  
  
  Discord Provider for NextAuth
&lt;/h2&gt;

&lt;p&gt;NextAuth allows developers to set up authentication for multiple services, like Google, Facebook, Apple, Github, etc. NextAuth calls these services and platforms as providers. In other words, these providers are services, and users can use them to log in to your application.&lt;/p&gt;

&lt;p&gt;We will use the Discord Provider for this article. Unlike other providers, Discord requires extra configuration to set up authentication. We must first sort those requirements.&lt;/p&gt;

&lt;p&gt;You must create an application on the Discord Developer Portal to access the Discord API and Discord's infrastructure. Then, take the Client ID and the Client Secret. You might need to reset the Client Secret for security purposes.&lt;/p&gt;

&lt;p&gt;You can proceed to the next step once you get the necessary credentials. If you cannot get the relevant information, do a basic search on your choice of browser, and someone will guide you.&lt;/p&gt;

&lt;h3&gt;
  
  
  NextJS App Initialisation
&lt;/h3&gt;

&lt;p&gt;If you haven't already, you must set up the NextJS application. Use the following command in your terminal to initiate a NextJS application and follow the steps.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the demonstration, I chose JavaScript over TypeScript (don't be angry at me) and TailwindCSS to demonstrate the authentication features in the front end. Also, I'm using the latest App Router to facilitate the API routes and a better experience overall.&lt;/p&gt;

&lt;p&gt;I haven't chosen the &lt;code&gt;src/&lt;/code&gt; configuration either. We're going to do everything inside the &lt;code&gt;app/&lt;/code&gt; directory. However, you can follow the same steps and adjust the code snippets for your application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Installing NextAuth
&lt;/h3&gt;

&lt;p&gt;You must use the following command to install NextAuth in your project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install next-auth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the installation, create a new API route to handle different requests related to authentication. First, create a folder named &lt;code&gt;api/&lt;/code&gt; inside the &lt;code&gt;app/&lt;/code&gt; directory. &lt;/p&gt;

&lt;p&gt;Then, add a nested folder inside the &lt;code&gt;api/&lt;/code&gt; directory and name it &lt;code&gt;auth/&lt;/code&gt;. Finally, make a directory called &lt;code&gt;[...nextauth]&lt;/code&gt; inside the &lt;code&gt;auth/&lt;/code&gt; directory. NextAuth requires this directory structure strictly to do its magic. &lt;/p&gt;

&lt;p&gt;To handle the incoming requests, create a &lt;code&gt;route.js&lt;/code&gt; file inside the &lt;code&gt;[...nextauth]&lt;/code&gt; folder. It is the dynamic route handler. Required Path: &lt;code&gt;app/api/auth/[...nextauth]/route.js&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjg8jvi8jugwnhdddbwuc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjg8jvi8jugwnhdddbwuc.png" alt="Directory Structure - Afan Khan LLC" width="290" height="139"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating API Route for NextAuth
&lt;/h3&gt;

&lt;p&gt;The dynamic route handler will store our NextAuth configuration and handle the incoming requests related to NextAuth.&lt;/p&gt;

&lt;p&gt;Start by importing NextAuth to the route handler file. Then, import the Discord Provider from NextAuth. After importing them, we will begin configuring NextAuth.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import NextAuth from "next-auth/next";
import DiscordProvider from "next-auth/providers/discord";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will need your Client ID and Client Secret now. Keep them handy. Now, you will create an object named AuthOptions. It will be an object with values required for the authentication. &lt;/p&gt;

&lt;p&gt;Remember, you must use the export keyword while initialising the object.&lt;/p&gt;

&lt;p&gt;We will use this object to access the current session in server components. By the way, even the session is server-based and not DB-related. Here's how your file should look like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import NextAuth from "next-auth/next";
import DiscordProvider from "next-auth/providers/discord";

export const AuthOptions = {
  providers: [
    DiscordProvider({
      clientId: "CLIENT_SECRET",
      clientSecret:
        "CLIENT_SECRET",
    }),
  ],
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you must initialise the authentication using the NextAuth function. This function requires the AuthOptions and its properties as parameters. Therefore, we will pass the AuthOptions object as a parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handler = NextAuth(AuthOptions);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You successfully integrated your configuration options with NextAuth. However, there's more. When someone uses Discord to log in to their account, Discord generates a code for the application to process and access the account of the signed-in user.&lt;/p&gt;

&lt;p&gt;We can use this unique code to get a serialized token. A token is a unique string of characters representing the signed-in user and acts as a keycard to access the Discord API. We can only access the Discord API if we have the Client Secret of the bot or the token of a valid Discord user.&lt;/p&gt;

&lt;p&gt;You can think of the token as the password to Discord's infrastructure and database but limited to the signed-in user.&lt;/p&gt;

&lt;p&gt;Some of you might be wondering where this unique code resides. Discord puts it in the URL where the application redirects the user after a successful sign-in. Here's how NextAuth helps us.&lt;/p&gt;

&lt;p&gt;Instead of putting our custom redirection URL, we will take the help of NextAuth. In the OAuth section of the selected application in the Discord Developer Portal, I will insert the following redirection URL, which will redirect the user to the route handler of NextAuth after a successful login.&lt;/p&gt;

&lt;p&gt;The redirection URL is the path to the dynamic route handler we had created earlier in our locally stored application. In the production build, you will replace the &lt;code&gt;localhost:3000&lt;/code&gt; with your domain name or VPS IP.&lt;/p&gt;

&lt;p&gt;Once the user logs in, they will get redirected to NextAuth's route handling system, and NextAuth will immediately swap the code for a token and store it.&lt;/p&gt;

&lt;h3&gt;
  
  
  NextAuth Callbacks
&lt;/h3&gt;

&lt;p&gt;I want the user to get redirected to a different page once the user logs in. I don't want them to remain on the default NextAuth page or get redirected to the root directory (homepage) by default. Therefore, I'll use a callback by NextAuth to handle the redirection.&lt;/p&gt;

&lt;p&gt;NextAuth provides callbacks that developers can configure for their unique use cases. NextAuth callbacks get invoked whenever specific events are triggered. For example, the &lt;code&gt;signIn()&lt;/code&gt; callback will execute when a user logs in.&lt;/p&gt;

&lt;p&gt;In our case, we will override the &lt;code&gt;redirect()&lt;/code&gt; callback. The callback takes two parameters, but we only need the baseUrl, which is usually the URL of the root directory (&lt;code&gt;localhost:3000/&lt;/code&gt;).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import NextAuth from "next-auth/next";
import DiscordProvider from "next-auth/providers/discord";

export const AuthOptions = {
  providers: [
    DiscordProvider({
      clientId: "YOUR_CLIENT_ID",
      clientSecret:
        "YOUR_CLIENT_SECRET",
    }),
  ],

  callbacks: {
    async redirect({ url, baseUrl }) {
      return baseUrl + "/dashboard";
    },
  },
};

const handler = NextAuth(AuthOptions);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will also export the result of invoking the &lt;code&gt;NextAuth()&lt;/code&gt; function from the route handler. Otherwise, GET and POST requests to access the sessions, or otherwise, will not work.&lt;/p&gt;

&lt;p&gt;Here's what your &lt;code&gt;route.js&lt;/code&gt; file should look like. You can replace the &lt;code&gt;/dashboard&lt;/code&gt; with whatever you desire.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import NextAuth from "next-auth/next";
import DiscordProvider from "next-auth/providers/discord";

export const AuthOptions = {
  providers: [
    DiscordProvider({
      clientId: "YOUR_CLIENT_ID",
      clientSecret:
        "YOUR_CLIENT_SECRET",
    }),
  ],

  callbacks: {
    async redirect({ url, baseUrl }) {
      return baseUrl + "/dashboard";
    },
  },
};

const handler = NextAuth(AuthOptions);

export { handler as GET, handler as POST };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Discord Permissions
&lt;/h2&gt;

&lt;p&gt;By default, you can only access the username and email of the signed-in user. You can try to use the Discord API and its endpoints to access more information, but Discord will deny the access. It is because Discord boosts privacy and security.&lt;/p&gt;

&lt;p&gt;You need the user's permission to access more information. You can take their permission while they are trying to log in. If you have noticed, Discord lists the permissions the user gives to the application when trying to log in.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4e060pqzc9dsylbow5p9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4e060pqzc9dsylbow5p9.png" alt="Discord Permissions Image - Afan Khan LLC" width="590" height="765"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you thought they were random, you were mistaken. The developer requests these permissions, and users usually overlook them. We can request permissions by adding them to the authorization URL. It's time to go back to the &lt;code&gt;route.js&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;DiscordProvider&lt;/code&gt; function, you must add another property named &lt;code&gt;authorization&lt;/code&gt;. The value of this property will depend on your requirements of the application. As I had stated earlier, I want to access the guilds of the signed-in user and display them.&lt;/p&gt;

&lt;p&gt;Therefore, I will ask for that permission, including a few others. You can find them in the Discord Developer Portal. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbka257pnj680q5rtip77.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbka257pnj680q5rtip77.png" alt="Permission Options - Afan Khan LLC" width="720" height="293"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Every permission name will be connected using the '+' symbol in the URL query params.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [
    DiscordProvider({
      clientId: "YOUR_CLIENT_ID",
      clientSecret:
        "YOUR_CLIENT_SECRET",
      authorization:
        "https://discord.com/api/oauth2/authorize?scope=identify+guilds",
    }),
  ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let us try to configure the front end to initiate the login process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configuring the front-end
&lt;/h2&gt;

&lt;p&gt;Since I initiated a new application, I will make modifications in the root directory. If you wish to put the login button elsewhere, you can do so. The steps remain the same.&lt;/p&gt;

&lt;p&gt;I will create a client component named &lt;code&gt;LoginUsingDiscord.jsx&lt;/code&gt; in the root directory to handle the &lt;code&gt;onClick&lt;/code&gt; events because my main &lt;code&gt;page.js&lt;/code&gt; file will remain in the default server component mode.&lt;/p&gt;

&lt;p&gt;Inside the component, I will import the &lt;code&gt;signIn()&lt;/code&gt; function from "next-auth/react" and invoke it whenever someone clicks on the "Login" button. We can pass one parameter to the &lt;code&gt;signIn()&lt;/code&gt; function. It is the name of the provider that the login button represents and should get invoked when clicked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import { signIn, signOut } from "next-auth/react";

export default function LoginUsingDiscord() {
  return (
    &amp;lt;section className="flex gap-8 items-center justify-center mt-12"&amp;gt;
      &amp;lt;p className="font-bold text-lg"&amp;gt;Login Using Discord&amp;lt;/p&amp;gt;
      &amp;lt;button
        onClick={() =&amp;gt; signIn("discord")}
        className="text-base py-3 px-4 bg-[#5865F2]"
      &amp;gt;
        Login
      &amp;lt;/button&amp;gt;
    &amp;lt;/section&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it. Once you click the button, you will get redirected to the Discord login interface. After the serialization of the token, you will get pointed towards your selected URL from the &lt;code&gt;redirect()&lt;/code&gt; callback. For me, it was &lt;code&gt;/dashboard&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After a successful login, you can access the session at &lt;code&gt;localhost:3000/api/auth/session&lt;/code&gt;. As I explained, this session will only have the username and email by default. I want to store the Discord user ID of the signed-in user and use it globally in the application.&lt;/p&gt;

&lt;p&gt;I will override another callback function named signIn() inside route.js. For security purposes, the token isn't accessible elsewhere in the application except in the boundaries of NextAuth.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async signIn({ account }) {
  const discordToken = account.access_token;

  return true;
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;I'm glad you found this article to be helpful. I'm writing an eBook to help people get jobs, earn outsized salaries, etc. It will take me a month or two to complete it. &lt;/p&gt;

&lt;p&gt;However, I've opened the waitlist for people to hop in early and benefit from the early-bird discount and exclusive access to the community to grow a personal brand. You will also meet like-minded people.&lt;/p&gt;

&lt;p&gt;Here's the link to sign up. I will not bore you with emails. But if I send an email, it will be worth looking out for.&lt;/p&gt;




&lt;p&gt;The &lt;code&gt;signIn()&lt;/code&gt; callback provides the user, account, session and other values as parameters. We only require the account parameter to retrieve the access token. &lt;/p&gt;

&lt;p&gt;In my dashboard project, I stored the token inside the DB after hashing it. However, I won't do the same here. I will try to access the information about the user using the token and print it in the console for simplicity.&lt;/p&gt;

&lt;p&gt;You must save the token somewhere to use the Discord API in routes or server components. Every request to the Discord API requires the Discord user token. Since I cannot make this article complex, I will not store the token anywhere and solely display the fetched data in the console.&lt;/p&gt;

&lt;p&gt;However, I will guide you on accessing the session on other pages in your application and display information later.&lt;/p&gt;

&lt;p&gt;Since I'm not storing the token anywhere, I cannot use it outside the &lt;code&gt;route.js&lt;/code&gt; file. Therefore, I will make an API request to the Discord API inside the &lt;code&gt;signIn()&lt;/code&gt; callback and show you how it works.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using the Discord API
&lt;/h2&gt;

&lt;p&gt;Let us continue modifying the &lt;code&gt;signIn()&lt;/code&gt; callback. I will fetch the information about the user and print it to the console for simplicity. The endpoints of these API requests are in the Discord Documentation.&lt;/p&gt;

&lt;p&gt;I'm making a GET request to the &lt;code&gt;api/users/@me&lt;/code&gt; endpoint provided by Discord to get an object with the information of the signed-in user. It doesn't matter whether the user is signed in. Each access token represents a unique user.&lt;/p&gt;

&lt;p&gt;The token expires and requires a renewal every month. I make those API requests on the user's behalf whenever I use their token. Discord treats me as a mediator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async signIn({ account }) {
   const discordToken = account.access_token;

   const discordUser = await fetch(`https://discord.com/api/users/@me`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${discordToken}`,
      },
    }).then((res) =&amp;gt; res.json());

    console.log(discordUser);

    return true;
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can pass the access token in the Authorization property of the header and get a response from the API endpoint if you did everything correctly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ojc2kxzao2kz36g711i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ojc2kxzao2kz36g711i.png" alt="Response from API" width="455" height="421"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I eventually added a sign-out button inside the LoginUsingDiscord component. I used the &lt;code&gt;signOut()&lt;/code&gt; function. It does not require any parameters because only one service can have an active session. Here's the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button
  onClick={() =&amp;gt; signOut()} className="text-base py-3 px-4 bg-[#ED4245]"&amp;gt;
  Sign Out
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Authentication is challenging to implement in most applications, and NextAuth makes it easier for us to do so. You learned how to create a session, allow users to log in using Discord, use the token to send API requests to the Discord API, etc.&lt;/p&gt;

&lt;p&gt;In the same way, you can use other providers, such as Google. I hope this article proved helpful to you. If you want to get a job as a software engineer, I suggest you join the waitlist.&lt;/p&gt;

&lt;p&gt;If you have any doubts, reach out to &lt;em&gt;&lt;a href="mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;&lt;/em&gt; or &lt;em&gt;&lt;a class="mentioned-user" href="https://dev.to/whyafan"&gt;@whyafan&lt;/a&gt;&lt;/em&gt; elsewhere.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>nextjs</category>
      <category>react</category>
      <category>nextauth</category>
    </item>
    <item>
      <title>Generator Functions &amp; Iterators in JavaScript</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Mon, 29 Apr 2024 10:54:23 +0000</pubDate>
      <link>https://dev.to/whyafan/generator-functions-iterators-in-javascript-14ml</link>
      <guid>https://dev.to/whyafan/generator-functions-iterators-in-javascript-14ml</guid>
      <description>&lt;p&gt;More often than not, interviewers ask about Generator Functions, the Yield Keyword, and Iterators. Most developers have no idea what they mean. &lt;/p&gt;

&lt;p&gt;Through this article, I will explain those complicated concepts using the fundamentals. Even I didn’t know they existed. I read about them in a QNA where developers were supposed to submit the names of intricate concepts.&lt;/p&gt;

&lt;p&gt;However, Generators have the same reputation as Closures. They are complicated because the crowd says so. Let us understand what Generators mean, the Yield keyword, and Iterators.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Iterators
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;By definition, iterators represent recurrence&lt;/strong&gt;. In JavaScript, as per MDN, Iterators and Generators bring the concept of iteration, i.e., repetition, directly into the core language. &lt;/p&gt;

&lt;p&gt;If you remember, we have loops in JavaScript to perform the repetition of code statements. We have methods, like &lt;code&gt;map()&lt;/code&gt;, too.&lt;/p&gt;

&lt;p&gt;However, the concept of Iterators in this context alongside Generators is different. Iterators that are custom and Generators use loops to perform their function. Generators and custom Iterators provide a mechanism for modifying the behaviour of the default iterators in the language, like loops.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const exampleArr = [1, 2, 3, 4, 5];

for(const val of exampleArr) {
    console.log(val);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;You are looking at a standard for-of loop. It doesn’t keep track of the current index or iteration number. It doesn’t know whether it should begin from the left or right-hand side. Unlike the traditional for-loop, we don’t mention a starting or ending index in the for-of loop.&lt;/p&gt;

&lt;p&gt;The loop moves from left to right sequentially because the array contains an iterator function instructing the for-of loop to iterate through a specific array in that sequence. It is the default behaviour.&lt;/p&gt;

&lt;p&gt;The for-of loop is an iterator because it executes the same statements on each array element repetitively. However, the for-of loop is a default iterator.&lt;/p&gt;

&lt;p&gt;Sometimes, you require a custom iterator that repeats specific code statements or traverses through a datatype in a specified manner. In massive applications, developers create custom data types. Those datatypes require custom iterators to access that data and manipulate them. Iterators are crucial when writing custom libraries.&lt;/p&gt;

&lt;p&gt;In the new context, an iterator is an object that defines the sequence of the iteration and potentially the values that will get returned when the code statements terminate. We can create custom iterators using the Iterator Protocol.&lt;/p&gt;

&lt;p&gt;Every iterator implements the Iterator Protocol with a &lt;code&gt;next()&lt;/code&gt; method that gets returned by it. The &lt;code&gt;next()&lt;/code&gt; method seems logical because the job of iterators is to traverse through elements from one index to another in a specific sequence. The method returns an object with two properties —&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;value&lt;/code&gt; — It holds the next value in the iteration sequence.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;done&lt;/code&gt; — It holds a boolean value. It represents whether the last value in the sequence has been traversed or consumed. If the &lt;code&gt;.value&lt;/code&gt; and &lt;code&gt;.done&lt;/code&gt; properties are present in an object, they represent the iterator’s return value.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The most common iterators in JavaScript are &lt;code&gt;forEach()&lt;/code&gt;, &lt;code&gt;filter()&lt;/code&gt;, &lt;code&gt;map()&lt;/code&gt;, etc., which return each value in a sequence. Those are default iterators. Now, let us create a custom iterator.&lt;/p&gt;
&lt;h3&gt;
  
  
  Custom Iterator
&lt;/h3&gt;

&lt;p&gt;Let’s reciprocate the for-loop and create a sequence that executes code statements for each iteration of an imaginary datatype. Remember, this is not how we make custom iterators. We use Generators, and the following example is the complicated approach. However, it is required to understand Generator Functions.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function customIterate(start = 0, end = Infinity, step = 1) {
  let nextIndex = start;
  let iterationCount = 0;

  return {
    // Returns a method to iterate over the iterator
    next() {
      // Stores an object throughout the iteration to keep track of the value and progress
      let result;
      // Indicates that iteration isn't finished
      if (nextIndex &amp;lt; end) {
        // Assigning those traditional value and done properties
        result = {
          value: nextIndex,
          done: false,
        };

        // Incrementing the index based on the steps
        nextIndex += step;
        // Incrementing the iteration count
        iterationCount++;

        // Returning the object
        return result;
      } else {
        return { value: iterationCount, done: true };
      }
    },
  };
}

// Storing the instance of the Iterator
const instanceOfIterator = customIterate(0, 20, 5);

// Invoking the next() method that iterates through the iterator
let result = instanceOfIterator.next();

// Till the .done property returns true
while (!result.done) {
  console.log(result.value);

  // invoking the next() method to update the result value for the while-loop and the iterator
  result = instanceOfIterator.next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;I will start with a function &lt;code&gt;customIterate()&lt;/code&gt;. It accepts your desired starting index, ending index, and step size as inputs. We will use default values if the user fails to provide them.&lt;/p&gt;

&lt;p&gt;Now, imagine an invisible runner flashing along numbers. Initially, they stand at the starting index. Inside the function, we prepare two trackers: &lt;code&gt;nextIndex&lt;/code&gt; tells us where the runner is now, and &lt;code&gt;iterationCount&lt;/code&gt; keeps tabs on how many laps they completed.&lt;/p&gt;

&lt;p&gt;The real magic happens in the &lt;code&gt;next()&lt;/code&gt; method. It is the engine that drives the iteration. If our runner has not crossed the finish line, it hands you the current position and prompts the running to continue with a &lt;code&gt;.done&lt;/code&gt; flag set to &lt;code&gt;false&lt;/code&gt;. Then, it hops forward based on the step size and keeps track of one more lap.&lt;/p&gt;

&lt;p&gt;But when the runner reaches the end, things change. Instead of another position, I offer the total number of laps as a farewell and wave a &lt;code&gt;.done&lt;/code&gt; flag of &lt;code&gt;true&lt;/code&gt;. The &lt;code&gt;.done&lt;/code&gt; property lets you know the exercise is over.&lt;/p&gt;

&lt;p&gt;To put this runner to work, you create an iterator object using &lt;code&gt;customIterate()&lt;/code&gt;. Then, you kick things off with a manual call to the &lt;code&gt;next()&lt;/code&gt;. The manual call gives you the initial position and gets the runner moving.&lt;/p&gt;

&lt;p&gt;The next step is a familiar friend: the &lt;code&gt;while&lt;/code&gt; loop. As long as the runner keeps going, you can access their current location through the &lt;code&gt;result.value&lt;/code&gt; property, do whatever cool stuff you want with it, and then hand them a new &lt;code&gt;next()&lt;/code&gt; call to keep the journey going.&lt;/p&gt;

&lt;p&gt;This custom iterator approach works, but it is like building a bicycle from scratch when a sleek, ready-made option exists. Now, this is where generator functions come in. They offer a much simpler and safer way to handle iterations, and I will dive into their world next.&lt;/p&gt;
&lt;h2&gt;
  
  
  What are Generator Functions
&lt;/h2&gt;

&lt;p&gt;We cannot create iterators that use the mechanism of the for-loop with standard Iterator Protocol. The solution is to use Generator Functions, but that's not the only reason anyone would want to use them.&lt;/p&gt;

&lt;p&gt;Standard Iterators store explicit state values inside their iterator functions. For example, the &lt;code&gt;nextStart&lt;/code&gt; and &lt;code&gt;iterationCount&lt;/code&gt; variables store the current progress or state of the iterator.&lt;/p&gt;

&lt;p&gt;Maintaining these states manually with variables is complicated without careful programming principles. Generator Functions are a powerful alternative that can maintain the states.&lt;/p&gt;

&lt;p&gt;Generator functions allow you to write the same iterative algorithm by creating a single function whose execution is not continuous. We can pause and resume at random intervals. These functions have a separate syntax.&lt;/p&gt;

&lt;p&gt;To define generators, we use the &lt;code&gt;function*&lt;/code&gt; keyword. There is an extra asterisk to the standard syntax. We're still trying to iterate through custom datatype but without explicit states. In addition to the strange syntax, JavaScript introduces a new keyword called &lt;code&gt;yield&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When we invoke generator functions, they don't initially execute the code. Instead, they return a specific object called a &lt;code&gt;Generator&lt;/code&gt;. We store that object inside another variable and invoke the &lt;code&gt;next()&lt;/code&gt; method or access the &lt;code&gt;.done&lt;/code&gt; and &lt;code&gt;.value&lt;/code&gt; properties through that object. Remember, Generators are beyond Iterators.&lt;/p&gt;

&lt;p&gt;Generator functions can run infinite loops because they can pause and resume their execution. We cannot have infinite loops without them because that would freeze our respective machines. The loop will continuously execute without any pauses.&lt;/p&gt;

&lt;p&gt;Generators allow us to insert those pauses and run infinite loops without worrying about freezing our computers. Until the &lt;code&gt;next()&lt;/code&gt; method gets called, the loop stays on hold after discovering the &lt;code&gt;yield&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;You will understand this in a bit. Depending on your application, you can use Generators to mimic the &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; functionality and deal with asynchronous code. Not to mention, they are also used to implement infinite scrolls on the front end.&lt;/p&gt;
&lt;h3&gt;
  
  
  What is the Yield Keyword
&lt;/h3&gt;

&lt;p&gt;By definition, the &lt;code&gt;yield&lt;/code&gt; keyword pauses and resumes the generator execution. The &lt;code&gt;yield&lt;/code&gt; keyword pauses the execution of the generator till it encounters another &lt;code&gt;next()&lt;/code&gt; method. Or till the next iteration comes around while using a loop. It is a distinctive sort of &lt;code&gt;return&lt;/code&gt; statement keyword used inside a generator.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;yield&lt;/code&gt; keyword is similar to &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;. Without the &lt;code&gt;async&lt;/code&gt; keyword, we cannot utilize &lt;code&gt;await&lt;/code&gt; and vice-versa. Similarly, we cannot use the &lt;code&gt;yield&lt;/code&gt; keyword without a generator function.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Generator Function
function* iterable() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
}

// Storing the returned object of the Generator
const iterableVal = iterable();

// Iterating
for (const val of iterableVal) {
  console.log(val);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;If you run this code, you will get a sequence of values printed to the console from 1 to 4. It prints all the values provided inside the generator function with the &lt;code&gt;yield&lt;/code&gt; keyword. Why? Let me explain.&lt;/p&gt;

&lt;p&gt;Using the for-of loop, JavaScript prints the results sequentially. The JS Engine detects a generator function that represents iterable and repetitive elements. The &lt;code&gt;yield&lt;/code&gt; keyword works in harmony with the function.&lt;/p&gt;

&lt;p&gt;Generators accept values and repeatedly return a new output. It returns the output using the &lt;code&gt;yield&lt;/code&gt; keyword sequentially with pauses at different intervals. The &lt;code&gt;yield&lt;/code&gt; keyword is like the &lt;code&gt;return&lt;/code&gt; keyword. Hence, those numbers show up in the console.&lt;/p&gt;

&lt;p&gt;Generators inherit the idea of an iterator that iterates and executes the same code on each element to get an output. Whenever JS encounters a &lt;code&gt;yield&lt;/code&gt; keyword, it prints the value followed by the keyword and resumes the execution. When it encounters another &lt;code&gt;yield&lt;/code&gt; keyword, it repeats the same process.&lt;/p&gt;

&lt;p&gt;Let us expand on that example. I will implement the same logic we had implemented earlier when understanding Iterators.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Example 2.0

// Generator Function
function* genIterator(start, end, step = 1) {
  for (let i = start; i &amp;lt;= end; i += step) {
    yield i;
  }
}

// Creates a Generator Object using the Generator Function
const generatorObject = genIterator(1, 20);

// Loops through the values of the Generator Object
for (const val of generatorObject) {
  console.log(val);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;I defined a function with a for-loop, passing in the same parameters. We do not need if-statements or manual step-by-step increments; the for-loop does the heavy lifting, returning an integer for each iteration.&lt;/p&gt;

&lt;p&gt;I stored the outcome of invoking the generator function inside another variable because generator functions return a &lt;code&gt;Generator&lt;/code&gt; object. In our case, we stored the object inside the &lt;code&gt;generatorObject&lt;/code&gt; variable after invoking &lt;code&gt;genIterator()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;yield&lt;/code&gt; statement returns the value stored in &lt;code&gt;i&lt;/code&gt; after each iteration. This lightweight approach lets you iterate through custom data types without crafting logic for each step. &lt;/p&gt;

&lt;p&gt;You can fetch information from the database and call the &lt;code&gt;yield&lt;/code&gt; keyword to pause and return the values instead of iterating continuously.&lt;/p&gt;

&lt;p&gt;Think of it this way: instead of gulping down a whole database at once, you can use &lt;code&gt;yield&lt;/code&gt; to savour each piece of information, pausing between bites. It ensures efficient handling of large datasets and provides ultimate control over the iteration process.&lt;/p&gt;

&lt;p&gt;If we do not use the &lt;code&gt;yield&lt;/code&gt; keyword, we can remove the for-of loop and invoke the &lt;code&gt;next()&lt;/code&gt; method repeatedly and manually. Since the &lt;code&gt;yield&lt;/code&gt; keyword pauses the generator, we must execute the &lt;code&gt;next()&lt;/code&gt; method to resume the execution. We use the for-of loop for the same reason.&lt;/p&gt;

&lt;p&gt;The for-loop replaces the massive logic inside the loop, and the for-of loop remains the same to continue the iterator. You can access the same &lt;code&gt;.done&lt;/code&gt; and &lt;code&gt;.value&lt;/code&gt; properties too.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* genIterator(start, end, step = 1) {
  for (let i = start; i &amp;lt;= end; i += step) {
    yield i;
  }
}

const generatorObject = genIterator(1, 5);

console.log(generatorObject.next().value);
console.log(generatorObject.next().done);

console.log(generatorObject.next().value);
console.log(generatorObject.next().done);

console.log(generatorObject.next().value);
console.log(generatorObject.next().done);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi2719t91mdo0a5nfwjht.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi2719t91mdo0a5nfwjht.png" alt="Output Image" width="147" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A few iterations are skipped in this approach because the &lt;code&gt;next()&lt;/code&gt; method gets executed. The paused iterations are resumed and then skipped while printing them. Instead, you can do the following.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* genIterator(start, end, step = 1) {
  for (let i = start; i &amp;lt;= end; i += step) {
    yield i;
  }
}

const generatorObject = genIterator(1, 5);

console.log(generatorObject.next());
console.log(generatorObject.next());
console.log(generatorObject.next());
console.log(generatorObject.next());
console.log(generatorObject.next());
console.log(generatorObject.next());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fap2oyswiil9apgcta24s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fap2oyswiil9apgcta24s.png" alt="Output 2 Image" width="395" height="211"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The simplest way to access the values directly without skipping iterations and manually executing the &lt;code&gt;next()&lt;/code&gt; method is to use a for-of loop, as shown in Example 2.0.&lt;/p&gt;

&lt;p&gt;If you still cannot understand the difference, let me explain. We all know that loops do not halt at any point to execute code statements. Once they start, they only stop at the end. &lt;/p&gt;

&lt;p&gt;We can use the &lt;code&gt;break&lt;/code&gt; keyword to stop the loop entirely or the &lt;code&gt;continue&lt;/code&gt; keyword to skip iterations. However, we can never pause the execution of a loop.&lt;/p&gt;

&lt;p&gt;It is where the &lt;code&gt;yield&lt;/code&gt; keyword becomes a convenient mechanism. We are using the for-loop inside the generator function. Instead of letting the for-loop complete its execution immediately, we use the &lt;code&gt;yield&lt;/code&gt; keyword to pause and resume its execution once we attain the desired data. &lt;/p&gt;

&lt;p&gt;It helps us manage database transactions, manipulation or handling data. Let me do DOM manipulation using a Generator Function.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;Generator Functions&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;button class="yield-result"&amp;gt;Click Here&amp;lt;/button&amp;gt;

    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="example.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* genIterator(start, end, step = 1) {
  for (let i = start; i &amp;lt; end; i += step) {
    yield i;
  }
}

const generatorObject = genIterator(1, 10);
const btn = document.querySelector(".yield-result");

btn.addEventListener("click", () =&amp;gt; {
  btn.textContent = generatorObject.next().value;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firhxjb2b9rydxfdux370.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firhxjb2b9rydxfdux370.gif" alt="Output 3 GIF" width="123" height="43"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I created a button element inside the HTML document. I attached an event listener, used the values fetched from the generator function after each pause and displayed it through the button.&lt;/p&gt;

&lt;p&gt;The last returned object from the &lt;code&gt;next()&lt;/code&gt; with the &lt;code&gt;.done&lt;/code&gt; property contained &lt;code&gt;true&lt;/code&gt; and indicated its competition after the entire generator completes its execution. The &lt;code&gt;.value&lt;/code&gt; property remained &lt;code&gt;undefined&lt;/code&gt; after resuming the last yield statement because there are no more values to return.&lt;/p&gt;

&lt;p&gt;When you invoke the function, it returns nothing except a &lt;code&gt;Generator&lt;/code&gt; object. Your code remains unexecuted. Previously, I had four yield statements inside a generator function and configured a for-of loop to iterate through them. Here’s how they worked.&lt;/p&gt;


&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://www.youtube.com/watch?si=9ZRhW9cPpzUXKYvg&amp;amp;v=6hzZwWeNTuQ&amp;amp;feature=youtu.be" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://res.cloudinary.com/practicaldev/image/fetch/s--MHuTgbtM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.ytimg.com/vi/6hzZwWeNTuQ/maxresdefault.jpg%3Fsqp%3D-oaymwEmCIAKENAF8quKqQMa8AEB-AH-CYAC0AWKAgwIABABGEYgTihlMA8%3D%26rs%3DAOn4CLB6dwaOKlCLZ_2OTrgbYG24rYFJTw" height="450" class="m-0" width="800"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://www.youtube.com/watch?si=9ZRhW9cPpzUXKYvg&amp;amp;v=6hzZwWeNTuQ&amp;amp;feature=youtu.be" rel="noopener noreferrer" class="c-link"&gt;
          Generator Function Explanation | Medium Article - YouTube
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          This is a small explanation for a concept in JavaScript called Generator Function. The entire video is meant for my medium article.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://res.cloudinary.com/practicaldev/image/fetch/s--o6g9yuU1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.youtube.com/s/desktop/5519da25/img/favicon.ico" width="16" height="16"&gt;
        youtube.com
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;The last &lt;code&gt;yield&lt;/code&gt; statement doesn't return &lt;code&gt;true&lt;/code&gt; for the &lt;code&gt;.done&lt;/code&gt; property because the generator function gets paused and doesn't finish the execution.&lt;/p&gt;

&lt;p&gt;We can have multiple generators at the same time. You can create another instance or object of the same or another generator and use a loop or manually invoke the &lt;code&gt;next()&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// First Generator
function* firstGen() {
  yield 1;
}

// Second Generator
function* secondGen() {
  yield 1;
}

const firstObj = firstGen();
const secondObj = firstGen();

// First Object
console.log(firstObj.next());
// Second Object
console.log(secondObj.next());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each instance of the same generator is separate and does not share values. You can create many of them. Let’s create an infinite loop and control it using a generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* infiniteLoop() {
  const username = "@whyafan";

    // Infinite Loop
  while (true) {
    yield username;
    console.log("Yielded!");
  }

    // Ignored because infinite loop never ends
  console.log("Can JS reach this statement?");
}

const infiniteExample = infiniteLoop();

console.log(infiniteExample.next());
console.log(infiniteExample.next());
console.log(infiniteExample.next());
console.log(infiniteExample.next());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I inserted a while-loop and conditioned it to execute the code statements inside it till the condition represented a truthy value. Of course, true will infinitely return a truthy value, so the loop will never stop. &lt;/p&gt;

&lt;p&gt;I yielded my username on all social media platforms through the while-loop. Whenever the returned object gets printed, the value will be &lt;a class="mentioned-user" href="https://dev.to/whyafan"&gt;@whyafan&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbprw5j0epsnjc2647rqx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbprw5j0epsnjc2647rqx.png" alt="Output Image 4" width="653" height="239"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Remember, the &lt;code&gt;.done&lt;/code&gt; property will never return true because this is an infinite loop. I invoked the &lt;code&gt;next()&lt;/code&gt; method four times and received the returned object in the same limit because the &lt;code&gt;yield&lt;/code&gt; keyword pauses the generator till an approaching &lt;code&gt;next()&lt;/code&gt; method gets discovered in the wild.&lt;/p&gt;

&lt;p&gt;Let us see how we can use the generator function for an array. We will access the array elements sequentially.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* arrayExample(start, end = Infinity, step = 1, array) {
  for (let i = start; i &amp;lt;= end; i += step) {
    yield array[i];
  }
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const arrayObj = arrayExample(0, 10, 2, array);

console.log(arrayObj.next());
console.log(arrayObj.next());
console.log(arrayObj.next());
console.log(arrayObj.next());
console.log(arrayObj.next());
console.log(arrayObj.next());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3ubyt8vs24l5ixbwykn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3ubyt8vs24l5ixbwykn.png" alt="Output Image 5" width="648" height="188"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lastly, let us see how we can use the &lt;code&gt;yield&lt;/code&gt; keyword to accept values passed as a parameter to the &lt;code&gt;next()&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* passingToNext() {
  let id = 1;

  while (true) {
        // This is where JS received the params
    const increment = yield id;

    if (increment !== null || increment !== undefined) {
      id += increment;
    } else {
      id++;
    }
  }
}

const yieldObj = passingToNext();
console.log(yieldObj.next());
console.log(yieldObj.next(2));
console.log(yieldObj.next(3));
console.log(yieldObj.next(4));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I created an infinite while loop like the previous examples. I purposely stored the result of the &lt;code&gt;yield&lt;/code&gt; keyword inside another variable because when you pass a value as a parameter to the &lt;code&gt;next()&lt;/code&gt; method, it takes that value and gives it to the &lt;code&gt;yield&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;When I passed &lt;code&gt;2&lt;/code&gt; to the &lt;code&gt;next()&lt;/code&gt; method, it received that integer through the &lt;code&gt;id&lt;/code&gt; variable with the &lt;code&gt;yield&lt;/code&gt; keyword and stored that inside the &lt;code&gt;increment&lt;/code&gt; variable. Then, I checked whether the received value is &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;. If yes, I incremented the &lt;code&gt;id&lt;/code&gt; variable without the value received from the user.&lt;/p&gt;

&lt;p&gt;Otherwise, I incremented the &lt;code&gt;id&lt;/code&gt; variable with the integer received by the user when they passed it as a value to the &lt;code&gt;next()&lt;/code&gt; method. &lt;/p&gt;

&lt;p&gt;You cannot pass a value to the first &lt;code&gt;next()&lt;/code&gt; method execution because &lt;code&gt;yield&lt;/code&gt; doesn’t exist during that iteration. It returns a result at the second iteration onwards.&lt;/p&gt;

&lt;p&gt;Remember, Generator functions can be a property of an object or the method of a class.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Avoid these 5 mistakes as a Web Developer</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Sun, 21 Jan 2024 07:53:31 +0000</pubDate>
      <link>https://dev.to/whyafan/avoid-these-5-mistakes-as-a-web-developer-2lgn</link>
      <guid>https://dev.to/whyafan/avoid-these-5-mistakes-as-a-web-developer-2lgn</guid>
      <description>&lt;p&gt;We all make mistakes. It's the most efficient way to learn, grow, and build experience. You can improve yourself if you reflect and learn from your mistakes. &lt;/p&gt;

&lt;p&gt;Most humans don't reflect on their mistakes. They criticize themselves for making those mistakes. A third person doesn't need to blame them; they do it themselves.&lt;/p&gt;

&lt;p&gt;I'll list ten mistakes that I've seen back-end engineers make throughout their Software Engineering career. Your current position doesn't matter when it comes to making mistakes. We all make them at any time in our careers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mistake 1
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Technical Debt. Over-engineering. Does that ring a bell?&lt;/strong&gt; Often, developers shift their focus to the technical side rather than understanding how the user will utilize the application. Based on those requirements, they don’t write their code. If back-end engineers used technologies based on the requirements, they would significantly reduce the required effort and cost.&lt;/p&gt;

&lt;p&gt;Mostly, beginners fall for this mistake. As they are new in the field, they don’t know what technologies will serve efficiently for the user while reducing the technical burden. The application becomes slow for the end user when more technologies and processing are required.&lt;/p&gt;

&lt;p&gt;New people in any field, hobby, or habit tend to overcomplicate the process. However, seniors reduce the effort and cost while using fewer technologies to save development and user time.&lt;/p&gt;

&lt;p&gt;Furthermore, Technical Debt indicates non-readable code. Write logic that other engineers can understand is the first rule of development. It means using industry-standard techniques and coding standards, such as this one, or writing variables in the CamalCase convention.&lt;/p&gt;

&lt;p&gt;Beginners feel a sense of pride when they use everything they possibly can. Later, the same choices become a headache when they make the application slower. It requires seniors to refactor the code, and that is a waste of time. The testing requirements and the chances of bugs increase with more code. Write less code.&lt;/p&gt;

&lt;p&gt;Avoid this mistake by keeping pride aside and choosing only the necessary technologies with the best industry standards. I made this mistake when I started learning front-end frameworks and libraries. It resulted in more code, more bugs, and massive refactoring costs. Follow the DRY, KISS, or YAGNI standards.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mistake 2
&lt;/h2&gt;

&lt;p&gt;I spent money on learning React from Udemy. I must use those skills and build every application with React. Right? NO. Don’t use the same technologies, libraries, or frameworks for every task. The choice of these frameworks depends on the problem that you are solving.&lt;/p&gt;

&lt;p&gt;React + Vite might work for intermediate Web Applications. However, it’s not suitable for performance-oriented applications. That’s when you shift and opt for SolidJS, NextJS, or any other framework to increase the performance.&lt;/p&gt;

&lt;p&gt;Based on the given task, change the technologies you use. Keep your fundamentals strong in the chosen language, like JavaScript, and keep switching technologies. &lt;/p&gt;

&lt;p&gt;Don’t stick to one technology. It limits your learning capabilities, and your application faces problems. Later, you would have to change those technologies, which you could have done in the first place.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mistake 3
&lt;/h2&gt;

&lt;p&gt;Individuals with bad intentions have outrageous techniques to attack your database and steal credentials. SQL injection is a common technique. If it is frequent, do people still fall for it? YES! &lt;/p&gt;

&lt;p&gt;It is because seniors might write code that prevents people from injecting queries that alter the database, but juniors aren’t aware of the intricacies of this field.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5zznkduutlze15wvku9u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5zznkduutlze15wvku9u.png" alt="Statista - 806081" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As of 2022, SQL Injection attacks received 33% of the responsibility for overall vulnerabilities caused in Web Applications. Due to the concatenation of unwanted strings with standard queries, individuals access your DB and usually execute DML commands.&lt;/p&gt;

&lt;p&gt;Avoid this mistake by passing specific required parameters inside queries rather than generalizing them. Don’t create a standard query for every operation to reduce your effort. It can lead to phone calls at 2:30 AM. Use multiple databases, and don’t keep all fruits in the same basket.&lt;/p&gt;

&lt;p&gt;Diversification is the key. Perform code reviews. Validate each string, especially the concatenated ones, while executing queries. Keep backing up the production DB.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mistake 4
&lt;/h2&gt;

&lt;p&gt;Are you someone who focuses on aesthetics instead of usability? It is a common rookie mistake. Beginner developers focus less on how the user utilizes the application and overcomplicate the designs. The UIUX might look beautiful till the testing phase.&lt;/p&gt;

&lt;p&gt;The business turnover decreases once the user utilizes your application because 95% of them cannot use it. Blame the complexity. Users desire a simple design. Users want interfaces that they have already seen before. Humans focus on their habits. They want to dedicate less effort to any task.&lt;/p&gt;

&lt;p&gt;Users will not use your application if you force them to learn a new pattern. Humans are familiar with specific patterns initiated by previous generations of designers. Young folks may change their habits. The majority of users will not.&lt;/p&gt;

&lt;p&gt;Design and build for the masses. Avoid this mistake by creating an interface using existing standards and user patterns or behaviour. Let the user buy your product with minimum effort. Social Media has created a solution for this mistake. There’s a reason why it is addictive. Less effort, more reward.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mistake 5
&lt;/h2&gt;

&lt;p&gt;For the moment, make a solution and write some code. We will see what happens down the road. We will make changes later, right? NO. Think of scalability from scratch. The amount of refactoring and development time required to fix bugs and errors isn’t ideal.&lt;/p&gt;

&lt;p&gt;From the start itself, choose specific technologies that solve the problem and understand how they are scalable based on the possible future metrics. For example, can we use React performance-specific tasks in the future if we decide to diversify? Nope. Should we then use it? No. Choose another technology.&lt;/p&gt;

&lt;p&gt;Most back-end engineers use the same set of technologies for every problem. Developers don’t think of the possible traffic and data transactions that could occur in the future. In 2013, hackers took advantage of the poorly scalable codebase of Snapchat and accessed the data of millions of users. You don’t want that to happen.&lt;/p&gt;

&lt;p&gt;Choose technologies that scale. Keep optimizing your code. Reduce the future development time and cost.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>How to become a Software Engineer in 2024</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Wed, 03 Jan 2024 11:57:47 +0000</pubDate>
      <link>https://dev.to/whyafan/how-to-become-a-software-engineer-in-2024-10ee</link>
      <guid>https://dev.to/whyafan/how-to-become-a-software-engineer-in-2024-10ee</guid>
      <description>&lt;p&gt;&lt;em&gt;There isn't a one-size-fits-all approach to becoming a Software Engineer.&lt;/em&gt; You might not know what to learn when you initially enter the field. To some degree, roadmaps enable you to start your journey and steer you in the right direction. &lt;/p&gt;

&lt;p&gt;For the same reason, this article consists of six different roadmaps within Software Engineering for you to get started.&lt;/p&gt;

&lt;p&gt;However, besides those roadmaps, one must focus on developing a list of required skills. I'll deliver that list in this article. Those crucial skills will enable you to work with teams, communicate your ideas, ace your interviews, and more. &lt;/p&gt;

&lt;p&gt;Let's take the &lt;strong&gt;Why-How-When&lt;/strong&gt; framework I picked for this article. Furthermore, I have a dedicated section called "&lt;strong&gt;What to look out for&lt;/strong&gt;" that expresses the lessons I learned throughout 2023 at the end. You must continue reading to learn from my mistakes and avoid making them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why
&lt;/h2&gt;

&lt;p&gt;More often than not, engineers face Impostor Syndrome. We experience challenges and setbacks that make us feel underskilled and overwhelmed. We feel like we don’t know enough. In the SWE world, there are moments where we feel utterly useless if we can’t build an application or implement a feature.&lt;/p&gt;

&lt;p&gt;These moments are easier to deal with when you know why you started. I remember I loved computers when I was a kid. I didn’t know enough about programming. But, I felt peace when I created something using them. Even if my projects meant crap compared to industry standards, I still made slight progress.&lt;/p&gt;

&lt;p&gt;Later on, I wanted to become an entrepreneur. I desired to build solutions. I saw that programming was booming. It was a high-paying industry. I wanted to create solutions and chose this field because I had experience writing HTML &amp;amp; CSS code. &lt;em&gt;Yes, that’s funny.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I recognised financial potential with a passion for doing something. I purchased courses with my startup money and upskilled daily. I reminded myself why I started. It was necessary to help me continue because humans often forget why they started doing something.&lt;/p&gt;

&lt;p&gt;We get lost in fancy roadmaps, videos, courses, etc. But it’s necessary to look back once in a while.&lt;/p&gt;

&lt;p&gt;“&lt;strong&gt;&lt;em&gt;How cool would it be if I could create a website and launch it on the World Wide Web for everyone to access and use?&lt;/em&gt;&lt;/strong&gt;” And that’s where it started. Forget other success stories. Focus on building yours. Your reason to enter this field can be for the money. That’s fine. We all have different goals.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The idea is to focus on yourself and not others.&lt;/em&gt; This field has many prodigies with early success stories. I don’t listen to their stories but spend time building mine. Learn from their mistakes instead of being jealous.&lt;/p&gt;

&lt;p&gt;Once you get your purpose straight, the next step is to understand how to conquer that purpose.&lt;/p&gt;

&lt;h2&gt;
  
  
  How
&lt;/h2&gt;

&lt;p&gt;Now, explore the ways to achieve your purpose. I deliberately chose the word “explore” because the choices committed during this step change once beginners turn intermediate. The method of doing something should change as you grow. You explore more options and understand the intricacies of the field.&lt;/p&gt;

&lt;p&gt;I can build a product or solution to solve a specific problem in a hundred different fields. I have the options. As a beginner, I must narrow them down based on my interests, experience, and knowledge. It can be UIUX design, Desktop Development, Data Science, or Front-End Web Development.&lt;/p&gt;

&lt;p&gt;I ask myself — “&lt;strong&gt;&lt;em&gt;Which of these fields most resonate with me? If I had to sit for 10 hours, which field would I choose and not get exhausted?&lt;/em&gt;&lt;/strong&gt;” For me, the answer was Web Development. I began and eventually explored all the other options with experience. I knew the answer because I had explored other options.&lt;/p&gt;

&lt;p&gt;Before choosing Web Development or SWE, I built various products using different technologies in diverse fields and industries. Try everything to figure out what gives you joy. Follow the principles of Ali Abdaal when he says that productivity requires us to do something we find joyful and fulfilling. &lt;/p&gt;

&lt;p&gt;As a beginner, you don’t know about the fields in an industry. The best way to learn is to search for it. Do a precise Google search of “&lt;em&gt;Which fields exist in Software Engineering&lt;/em&gt;” and examine the results. Make categories based on future potential in growth and finance because you don’t want to pick a dead field with no future scope.&lt;/p&gt;

&lt;p&gt;Learn the fundamentals of each option. You will get a gist of how they work based on videos and articles concerning the topic available on the Internet. With a strong foundation, you can learn the complex concepts effortlessly. Strike a balance between theoretical and practical. Create more problems and build solutions using them.&lt;/p&gt;

&lt;p&gt;Look at the financial future of your desired choice. Luckily, Web Development had a foreseeable future. It scaled as required. At that time, it was one of the highest-paying jobs. I selected it for the same reason. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Passion and Interest are pointless if you cannot make money. It’s like building a loss-making business without the potential to grow.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here are a few roadmaps or guides with the names of central technologies that I believe have potential in the future. Furthermore, do your research. I don’t know you, your skillsets, or your past. Choose the right fit for yourself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Web Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2x6qgLud--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqp9mhcou1dw6ii60d8t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2x6qgLud--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqp9mhcou1dw6ii60d8t.png" alt="Web Developemnt Roadmap" width="800" height="526"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Blockchain Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2RI7GWNe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbepcfw21g32qrhxynkm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2RI7GWNe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbepcfw21g32qrhxynkm.png" alt="Blockchain Development Roadmap" width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Science
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZB5Gi4Wo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onr0nljm26uzagx2zgwq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZB5Gi4Wo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onr0nljm26uzagx2zgwq.png" alt="Data Science Roadmap" width="800" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Mobile Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w5gS4WAm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7srk2htyrdvrqtf905n0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w5gS4WAm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7srk2htyrdvrqtf905n0.png" alt="Mobile Development Roadmap" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Desktop Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bw0R0lSb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mvh2hds47o8zi87bpmi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bw0R0lSb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mvh2hds47o8zi87bpmi.png" alt="Desktop Developement Roadmap" width="800" height="518"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Game Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8LdB2aa6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhpemeaiqoqmlb2jyiq4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8LdB2aa6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhpemeaiqoqmlb2jyiq4.png" alt="Game Development Roadmap" width="800" height="439"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  When
&lt;/h2&gt;

&lt;p&gt;Most people know what they want to do. They have the perfect plan and the best roadmaps on the Internet from the most experienced engineers. Yet, they fail to take action because of an excuse.&lt;/p&gt;

&lt;p&gt;Here are a few steps to take consistent actions —&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Set a time to learn and practice every day for at least half an hour.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Interact with other engineers on platforms like Twitter (X) and share your knowledge.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you want to build something, put it in a to-list and assign a deadline.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;The best time to learn was yesterday, but you can still conquer today.&lt;/strong&gt; Take the necessary steps after reading this article. Go to the documentation of the language you wish to learn or buy the Udemy course you always wanted to learn.&lt;/p&gt;

&lt;p&gt;Watch the course daily for a blocked duration and practice while watching those videos. Focus on being practical because there’s nothing more vital than knowing how to fix a bug that most engineers cannot.&lt;/p&gt;

&lt;p&gt;Experience and a spark to explore for whatever purpose bring you the leverage to build whatever you want. Make things easier for you. Don’t make big goals that overwhelm you. Instead, &lt;em&gt;improve yourself and achieve your goals with slight (0.1%) progress daily.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Practising daily helps more than you can imagine. With fundamentals, you can also take advantage of Artificial Intelligence tools.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to look out for
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The first lines of code you write by yourself will seem difficult. For the same reason, experienced engineers suggest picking a field with a minimum entry barrier, like Web Development. Don’t get scared or frustrated. Remember, we all have been there. Instead, focus on reading and learning more. In the SWE world, the resources are abundant.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Don’t jump to complex concepts or techniques. If you know how to write a for-loop, it doesn’t mean you can deal with data structures and algorithms already. It takes time to make progress. Avoid overwhelming yourself. Focus on the basics.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid finding an answer directly. Spend a few hours, if not days, to understand why a specific bug or error keeps appearing in your code. Find the root cause. When you know why a problem occurs, it’s easier to solve it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid directly writing code. When you are assigned a problem, start by building a strategy. In Interviews, the employers test your thinking process. Before writing code, I design a flowchart or mindmap of how to solve a specific problem and what to use.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Take a break. Whenever I encounter a bug that overloads my cognitive ability to think and solve, I go on a small ride to the nearest cafe and spend time with my friends. I kept myself distracted from work and came back with a fresh mind.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid copy-pasting code. If you ask an LLM for a code snippet, you must understand the logic before you use it. And while using it, try to write the entire code yourself and explain each keyword with their usage. It’s tempting to ask GPT models to write code. However, you are at the stage of learning, not implementing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use GPT models to explore and expand your avenues. I once saw a code snippet on Twitter about a JavaScript-related trick. I couldn’t understand specific pieces of the logic. I asked ChatGPT to explain the purpose of a combination of operators together and fill the necessary gaps to understand the code snippet.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid excessively learning and start building. The main joy of being an engineer is to help others create their projects and allow them to help you create yours. Contribute to open-source and build open-source projects. Your theoretical knowledge will solidify and stay with you for the longest time when you practice and implement it daily.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Start by building smaller projects. Again, don’t overwhelm yourself. When I decided to learn the Swift language, I built a Pomodoro Timer for Apple Watch, Apple TV, and MacBooks. I started small and took baby steps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reflect on your mistakes and fundamental gaps in your learning. There are situations where you cannot implement a specific feature using a technology. At that point, write down the technology and features you failed to implement. After a bit of time, revert and start working on that gap. I couldn’t work with component libraries, so I took a project that allowed me to use those component libraries and build a project.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Build valuable connections. Life goes beyond work. I focused on only making friends who could help me earn more money. It made me shallow because I didn’t interact with them. I wasn’t friendly. I began treating everyone as a friend who is valuable to my career, but not limited to that, and became a positive person. I shared my problems; they shared theirs. We fixed bugs together, taught concepts to each other, etc.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To succeed, you must try, fail, and then retry. We’re all humans. And that’s why we should give ourselves time to adapt to problems we face today with the knowledge of yesterday.&lt;/p&gt;




&lt;p&gt;If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;. I'd love to get your feedback through the comments section.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>How to create IIFE functions in JavaScript?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Fri, 29 Dec 2023 13:51:49 +0000</pubDate>
      <link>https://dev.to/whyafan/how-to-create-iife-functions-in-javascript-49n2</link>
      <guid>https://dev.to/whyafan/how-to-create-iife-functions-in-javascript-49n2</guid>
      <description>&lt;h2&gt;
  
  
  Introduction to IIFE
&lt;/h2&gt;

&lt;p&gt;I’m sure most people aren’t aware of the IIFE concept in JavaScript. It stands for Immediately-Invoked Function Expressions (IIFE). They were popular during the ES5 era for their infamous solution to the hoisting problems in JavaScript.&lt;/p&gt;

&lt;p&gt;IIFE represents functions that execute the statements within them immediately without a function call. They do not have a function name for JavaScript to invoke it. It runs the code statements once the JavaScript engine discovers the function definition.&lt;/p&gt;

&lt;p&gt;They are like the criminals that start shooting randomly without any prior warning in the air once they get caught.&lt;/p&gt;

&lt;p&gt;It acts like any other statement inside JavaScript that executes once the engine scans it but inside a function. One can even declare them as asynchronous functions for those backend operations whenever required.&lt;/p&gt;




&lt;h4&gt;
  
  
  I launched a new free eBook!
&lt;/h4&gt;

&lt;p&gt;The eBook is a 4-step framework to build projects and learn skills that enable you to attain practical experience in your field and become a developer whom recruiters and clients cannot say "No" during the discovery call.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;a href="https://afankhan.gumroad.com/l/build-to-solve-problems"&gt;https://afankhan.gumroad.com/l/build-to-solve-problems&lt;/a&gt;
&lt;/h4&gt;




&lt;h2&gt;
  
  
  Why use IIFE?
&lt;/h2&gt;

&lt;p&gt;You can use the IIFE pattern whenever you wish to execute non-repetitive code lines that are not required in your program later and avoid populating the global namespace with unnecessary global variables.&lt;/p&gt;

&lt;p&gt;Since variables cannot escape the block scope of a function except variables declared using the &lt;code&gt;var&lt;/code&gt; keyword, the temporary IIFE function allows them to stay trapped as local variables. It is precisely helpful in Functional Programming.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use strict";

// Function Declaration

(function () {
  const password = `uVkJa@^FmAHG7QW$(B+j`;
  console.log(`User's social media password: ${password}`);
})();

// Arrow Function

(() =&amp;gt; {
  console.log(`This is the functional expression version of an IIFE`);
})();

// Asynchronous Arrow Function

(async () =&amp;gt; {
  await fetch("https://api.quotable.io/quotes/random")
    .then((res) =&amp;gt; res.json())
    .then((data) =&amp;gt; {
      console.log(`Random Quote (Only Once): ${data[0].content}`);
    });
})();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We must precisely wrap a function declaration or arrow function with or without the async keyword to define an IIFE function. Once the engine reaches the function definition, it will execute the statements inside the function and discard the local variables after their usage.&lt;/p&gt;

&lt;p&gt;It disappears after the first execution. You must also add &lt;code&gt;()&lt;/code&gt; after closing an IIFE for JavaScript to understand this anonymous function. The function is still an expression and will not execute instantly without inserting the parentheses.&lt;/p&gt;

&lt;p&gt;It’s not a feature but a pattern developed by engineers using JavaScript. IIFE isn’t used often in JavaScript anymore because the ES6-based &lt;code&gt;const&lt;/code&gt; and &lt;code&gt;let&lt;/code&gt; keywords create custom block scopes inside a code block.&lt;/p&gt;

&lt;p&gt;Before ES6 and so far, many people utilized &lt;code&gt;var&lt;/code&gt;, and IIFE makes sense for them. Variables with &lt;code&gt;var&lt;/code&gt; are accessible outside standard code blocks because of a concept called Hoisting, and developers created this pattern to prevent the data from merging with the remaining variables in the global environment.&lt;/p&gt;

&lt;p&gt;If you wish to invoke a function once besides its global namespace benefits, the IIFE design pattern is your best bet.&lt;/p&gt;




&lt;p&gt;That's it. If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;. Otherwise, Twitter (X) is the easiest way to reach out - @justmrkhan.&lt;/p&gt;

&lt;p&gt;I'd love to get your feedback through the comments section.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
      <category>react</category>
    </item>
    <item>
      <title>What is Inheritance and the Prototype Object in JavaScript?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Thu, 07 Dec 2023 15:57:27 +0000</pubDate>
      <link>https://dev.to/whyafan/what-is-inheritance-and-the-prototype-object-in-javascript-1jb9</link>
      <guid>https://dev.to/whyafan/what-is-inheritance-and-the-prototype-object-in-javascript-1jb9</guid>
      <description>&lt;p&gt;Most developers don’t know that the beloved scripting language also has secured OOP paradigm capabilities under its belt. These are features that JavaScript developers should know, but they don’t.&lt;/p&gt;

&lt;p&gt;Irrespective of how JS implements these features, they work like a scripting language with strange quirks behind the scenes.&lt;/p&gt;

&lt;p&gt;JavaScript never ceases to amaze me, and I don’t want to keep all this to myself. Let’s begin by understanding the concept of Inheritance and JS’ approach towards it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inheritance
&lt;/h2&gt;

&lt;p&gt;The Inheritance &lt;em&gt;implementation&lt;/em&gt; in OOP-based languages, like Java, differs from JavaScript. Those languages were programming languages since their inception.&lt;/p&gt;

&lt;p&gt;However, JavaScript stems from a different pair of roots. It implements all these features in a strange ritual and has various operations in the background to make those features possible.&lt;/p&gt;

&lt;p&gt;JS requires workarounds to implement such features because Brendan Eich did not want it to operate like an OOP-based language. &lt;em&gt;However, the concept of Inheritance for Java and JavaScript remains the same.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The primary Inheritance idea is to pass down properties and methods of a class to another new child class or object without creating duplicate values.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why use Inheritance?
&lt;/h3&gt;

&lt;p&gt;Assume there is Class A and Class B. If class A has a property that class B requires, then Class B can create that property again. But that would be repetitive and a violation of the DRY principle.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Software engineering is all about reusability and readability&lt;/em&gt;. If developers create duplicate variables, fellow engineers and themselves will face problems understanding the logic and where those variables reside.&lt;/p&gt;

&lt;p&gt;That’s why we use Inheritance. &lt;em&gt;It allows child classes and objects to inherit properties, values, and methods from parent classes and objects that have them already to avoid writing the same logic repeatedly.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For OOP-based languages, Inheritance is a way to securely grab values from one class to another, as each class represents a component or feature in the application.&lt;/p&gt;

&lt;p&gt;Similarly, when your grandparents or parents are wealthy, your requirements to work hard are significantly lower because top-level members satisfy those requirements already.&lt;/p&gt;

&lt;p&gt;When parents are wealthy, some children continue their legacy while others inherit and enjoy their lives. It is optional to have more properties, not the real estate ones, but the ones in objects, after inheriting some of them, which is the same in programming.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Child classes serve more purpose even after inheriting properties and methods from parent classes.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  How is Inheritance implemented in JS?
&lt;/h3&gt;

&lt;p&gt;JavaScript is not an object-oriented language. Inheritance is derived from languages like Java, C++, and others because they require Classes to write any code.&lt;/p&gt;

&lt;p&gt;They preach the idea of secure code. To write a print statement in Java, you write them inside Classes, so the requirement of Inheritance there becomes viable.&lt;/p&gt;

&lt;p&gt;Typically, developers use classes with constructors to implement Inheritance in those languages with zero object requirements.&lt;/p&gt;

&lt;p&gt;However, JavaScript desires to stay unique. It uses objects to implement Inheritance. That’s standard for JavaScript developers, but OOP-based developers perceive it as a nightmare.&lt;/p&gt;

&lt;p&gt;Trust me, objects are a part of a massive syntactical sugar play. JavaScript implements it using a mechanism called Prototype alongside a few constructor functions.&lt;/p&gt;

&lt;p&gt;First, I will explain Inheritance with Classes in JavaScript since most developers are familiar with it concerning classes in languages like Java. I will also explain the purpose of Classes for a bit more background.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is class-based Inheritance?
&lt;/h2&gt;

&lt;p&gt;The coding world would look difficult without a class for OOP developers. Anyone would hate writing duplicate code. For instance, look at the following example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use strict";

// Model 1 of Porsche
const car1 = {
  brand: "Porsche",

  model: "911 GT3",
  topSpeed: "318 KM/h",
  acceleration: "3.4",

  carDetails: function () {
    console.log(
      `This is a ${this.model} by ${this.brand} with a top speed of 
        ${this.topSpeed} and accelerates from 0 to 100 KM/h in 
        ${this.acceleration} seconds`
    );
  },
};

// Model 2 of Porsche
const car2 = {
  brand: "Porsche",

  model: "718 Cayman GT4 RS",
  topSpeed: "315 KM/h",
  acceleration: "3.4",

  carDetails: function () {
    console.log(
      `This is a ${this.model} by ${this.brand} with a top speed of 
        ${this.topSpeed} and accelerates from 0 to 100 KM/h in 
        ${this.acceleration} seconds`
    );
  },
};

car1.carDetails();
car2.carDetails();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I created two objects for two cars from the same brand - Porsche. You can notice the repetitive properties and methods between both objects.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;brand&lt;/code&gt; name, &lt;code&gt;acceleration&lt;/code&gt; property, and the &lt;code&gt;carDetails()&lt;/code&gt; method are the same in both objects. There's no difference in their values or syntax. It is called &lt;strong&gt;Code Duplication&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The property values, such as &lt;code&gt;acceleration&lt;/code&gt;, might change later, but the &lt;code&gt;carDetails()&lt;/code&gt; method will display the same properties and remain unmodified. Why should we duplicate and keep it in two places if we cannot modify the method? That is why the world introduced Classes.&lt;/p&gt;

&lt;p&gt;Classes allow us to write the template and boilerplate for such scenarios. We can insert the names of properties and write functions, like &lt;code&gt;carDetails()&lt;/code&gt;, inside them using those properties. &lt;/p&gt;

&lt;p&gt;Based on the details from these classes, developers create objects, which are instances of Classes.&lt;/p&gt;

&lt;p&gt;Objects copy the barebone details from Classes and modify them to their needs and uniqueness. Not only duplication, but if you wish to alter the &lt;code&gt;carDetails()&lt;/code&gt; method, there is no unified approach. &lt;br&gt;
Only one method inside one object will get modified at a time.&lt;/p&gt;

&lt;p&gt;I am sure you do not dream of sitting and implementing the same modifications to each similar object on a chill weekend. Hence, let me turn the above code into a version that uses a class. I'm sure you are starting to see the purpose of Inheritance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class porscheCar {
  // Constructor
  constructor(carModel, carTopSpeed, accl) {
    this.model = carModel;
    this.topSpeed = carTopSpeed;
    this.acceleration = accl;
  }

  // Default Brand Name
  brand = "Porsche";

  // Display Function

  carDetails() {
    const result = `This is a ${this.model} by ${this.brand} with 
    a top speed of ${this.topSpeed} and accelerates from 0 to 100 
    KM/h in ${this.acceleration} seconds`;

    return result;
  }
}

// Creating new Objects of porscheCar Class
const car1 = new porscheCar("911 GT3", "318 KM/h", "3.4");
const car2 = new porscheCar("911 GT3", "318 KM/h", "3.4");

console.log(car1.carDetails());
console.log(car2.carDetails());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We had two problems - Code Duplication and the need to modify multiple objects and their methods by hand. We solved the first problem, but we will need to fix the second problem.&lt;/p&gt;

&lt;p&gt;We cannot modify the methods of the objects belonging to a class directly. We cannot do &lt;code&gt;car1 = function() {}&lt;/code&gt; because it would only update &lt;code&gt;car1&lt;/code&gt; and not &lt;code&gt;car2&lt;/code&gt; together. That would require us to modify the class.&lt;/p&gt;

&lt;p&gt;However, before we tackle the second problem, I want to talk about extending classes. We're diving deeper into the Prototype mechanism to modify the objects together through code and not manual modifications.&lt;/p&gt;

&lt;p&gt;But what if I had another class called &lt;code&gt;mercedesCar&lt;/code&gt; and wanted the same properties and methods with other unique values? As I explained earlier, we have to avoid code duplication.&lt;/p&gt;

&lt;p&gt;Hence, we will use the &lt;code&gt;extends&lt;/code&gt; keyword in JavaScript that passes down the properties and methods of &lt;code&gt;porscheCar&lt;/code&gt; to &lt;code&gt;mercedesCar&lt;/code&gt; and perform Inheritance. Remember that we still need to solve the second modification problem, but I will tackle this first because I prefer Benz.&lt;/p&gt;

&lt;h3&gt;
  
  
  Extending Classes
&lt;/h3&gt;

&lt;p&gt;Traditionally, this is how Inheritance would take place in other languages using the extends keyword.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class mercedesCar extends porscheCar {
  constructor(carModel, carTopSpeed, accl) {
    super();

    this.model = carModel;
    this.topSpeed = carTopSpeed;
    this.acceleration = accl;
    this.brand = "Mercedes";
  }
}

const mb1 = new mercedesCar("300 SLR", "290 km/h", "7.7", "1955");
console.log(mb1.carDetails());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The constructor takes the information from the parameters while creating the object and delivers it to the extended parent &lt;code&gt;porscheCar&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;Constructors inside classes initialize an object and assign unique values for the boilerplate inside classes. The &lt;code&gt;super()&lt;/code&gt; method invokes the constructor of the extended &lt;code&gt;porscheCar&lt;/code&gt; class and is necessary because we try to access the variables of &lt;code&gt;porscheCar&lt;/code&gt; inside &lt;code&gt;mercedesCar&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we do not include &lt;code&gt;super()&lt;/code&gt;, we cannot use the &lt;code&gt;this&lt;/code&gt; keyword to access and assign new variables to the &lt;code&gt;porscheCar&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;We need to access and assign values to the &lt;code&gt;porscheCar&lt;/code&gt; class because the &lt;code&gt;carDetails()&lt;/code&gt; method belongs to the &lt;code&gt;porscheCar&lt;/code&gt; class. &lt;/p&gt;

&lt;p&gt;The carDetails() method requires the model name, top speed, brand name, and acceleration data of the legendary 300 SLR to print to the console.&lt;/p&gt;

&lt;p&gt;Therefore, we used &lt;code&gt;super()&lt;/code&gt; and provided the value for its properties using the constructor. I created an instance of the &lt;code&gt;mercedesCar&lt;/code&gt; class and invoked the &lt;code&gt;carDetails()&lt;/code&gt; method even though it belonged to the porscheCar Car class because I had called &lt;code&gt;super()&lt;/code&gt; to deliver the values of Mercedes to Porsche 🏎️.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prototype
&lt;/h2&gt;

&lt;p&gt;JavaScript is different. It doesn’t like the standard behaviour of the &lt;code&gt;class&lt;/code&gt; and &lt;code&gt;extends&lt;/code&gt; keywords. It does something else under the hood even though it uses the &lt;code&gt;class&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;In the example above, I inherited the methods and properties of one class to another, which is the traditional approach. But now, let us revert to the second problem we had earlier.&lt;/p&gt;

&lt;p&gt;We had two objects called &lt;code&gt;car1&lt;/code&gt; and &lt;code&gt;car2&lt;/code&gt; separately and then transferred to the &lt;code&gt;porscheCar&lt;/code&gt; class to solve the first problem of code duplication.&lt;/p&gt;

&lt;p&gt;After creating the class and initiating those objects, I wanted to modify the statements inside the &lt;code&gt;carDetails()&lt;/code&gt; method. However, I cannot assign a new function because I use a class to wrap those objects and methods. They are secure and cannot be modified directly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;car1.carDetails = function() {}...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will not work. The &lt;code&gt;car2&lt;/code&gt; object will still have the old &lt;code&gt;carDetails()&lt;/code&gt; method even if, theoretically, someone modifies the &lt;code&gt;carDetails()&lt;/code&gt; method inside the &lt;code&gt;car1&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;In other languages, you can modify the methods of an object independently because those languages create a copy of everything inside a class and give that to its objects. We can do that in JS but with its disadvantages.&lt;/p&gt;

&lt;p&gt;We cannot modify the method of any object related to a class because those methods do not belong to the objects in the first place. In Java, after building the same foundation for both objects using the boilerplate code in a class, I could if I wanted the method in &lt;code&gt;car1&lt;/code&gt; to stay different from &lt;code&gt;car2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We cannot do that in JS because it doesn’t copy the contents of a class and give it to the object. Instead, JavaScript lends those methods inside the class to those objects through a reference. In reality, those methods still reside inside the class and are given for rent to its objects while they want.&lt;/p&gt;

&lt;p&gt;It is called the prototype mechanism. Each object has an interlinked copy object called its prototype. Each object has its prototype, and other objects cannot modify it.&lt;/p&gt;

&lt;p&gt;A prototype of an object or value is a copy of the properties and methods present inside the object. &lt;/p&gt;

&lt;p&gt;In the same way, a Class has a prototype of its own. This prototype gets shared with each object inside it, and those objects can use that to invoke methods and play with its properties but not modify it.&lt;/p&gt;

&lt;p&gt;I must modify the prototype of the &lt;code&gt;porscheClass&lt;/code&gt; class if I want to solve our second problem of changing the methods of a Class. These changes should appear for each object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;porscheCar.prototype.carDetails = function () {
  const result = `You are looking at ${this.brand}'s 
    ${this.model} with a top speed of ${this.topSpeed} and 
    swifts from 1 to 100 KM/h in ${this.topSpeed} seconds.`;

  return result;
};

console.log(car1.carDetails());
console.log(car2.carDetails());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code for the class and the creation of &lt;code&gt;car1&lt;/code&gt; and &lt;code&gt;car2&lt;/code&gt; remain the same. I modified the string inside the &lt;code&gt;carDetails()&lt;/code&gt; method using the prototype property binded to the class.&lt;/p&gt;

&lt;p&gt;That property allows us to access the properties and methods of the respective class and alter them outside the class. It isn’t secure at all, and I know the OOP folks are shouting at me virtually through the screen, but as I said, JavaScript is not for this.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;class&lt;/code&gt; keyword is simply sugarcoating the concept of OOP. Developers requested that keyword. On the face of it, they gave the feature. But under the hood, the Prototype mechanism initiates the objects and shares the properties and methods of the classes with its properties instead of giving them a copy.&lt;/p&gt;

&lt;p&gt;Objects initiated using Classes can have unique properties when their properties inside the class initialize using the &lt;code&gt;this&lt;/code&gt; keyword because that keyword refers to each object individually and not as a whole.&lt;/p&gt;

&lt;p&gt;Therefore, I will get the properties of &lt;code&gt;car1&lt;/code&gt; returned as an object because they are uniquely defined. However, the &lt;code&gt;carDetails()&lt;/code&gt; method will remain in the prototype because that method is typical for each object, including &lt;code&gt;car2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1j9bpadlxmzmhtz0w7rn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1j9bpadlxmzmhtz0w7rn.png" alt="Car1 Object Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;[[Prototype]]&lt;/code&gt; represents the Prototype object and belongs to the &lt;code&gt;porscheCar&lt;/code&gt; class. The square brackets represent an object that cannot be modified. &lt;/p&gt;

&lt;p&gt;It is how JavaScript represents Prototypes objects, but there’s also &lt;code&gt;__proto__&lt;/code&gt;. However, it is deprecated and controversial, so I will let it stay in the shadows.&lt;/p&gt;

&lt;h2&gt;
  
  
  Constructors and Classes
&lt;/h2&gt;

&lt;p&gt;Try to observe the following code. Maybe there’s not more than an empty object to observe. And still, the output has a Prototype with selective methods even though the object is empty.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log({});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fheoy4iniiq6a0pcqrq03.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fheoy4iniiq6a0pcqrq03.png" alt="Empty Object Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The JavaScript language has a set of default methods for each object in the language to access and use. You can use them even if they are not explicitly defined. As I explained earlier, each object connects to a copy of itself and creates a Prototype chain.&lt;/p&gt;

&lt;p&gt;Each empty object points to an unnamed object, and your objects inherit properties and methods from that nameless object. It happens because each object in JavaScript is an instance of a class named "Object" with a capital "O".&lt;/p&gt;

&lt;p&gt;Each object in JavaScript inherits the Object constructor information or class and displays that irrespective of whether the object has anything inside it.&lt;/p&gt;

&lt;p&gt;You will find the default properties of the Object class because &lt;code&gt;car1&lt;/code&gt; is an object after all if you try to access the Prototype of the &lt;code&gt;car1&lt;/code&gt; object Prototype. It does not work with Objects only, and the same principles apply to Arrays.&lt;/p&gt;

&lt;p&gt;And finally, the object-based inheritance.&lt;/p&gt;

&lt;h1&gt;
  
  
  Object-based Inheritance
&lt;/h1&gt;

&lt;p&gt;In JavaScript, there are a few ways one can initiate an object. We have been using the first and most preferable approach throughout this article using the &lt;code&gt;{}&lt;/code&gt; object literal. However, we can also create them using a function. Take the example below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createBenz(modelName, brandName, engine, releaseYear) {
  this.model = modelName;
  this.brand = brandName;
  this.engine = engine;

  function returnDetails() {
    console.log(
      `You are looking at ${this.brand}'s ${this.model} with a 
       ${engine} engine`
    );
  }
}

const mb2 = new createBenz("S-Class S680", "Mercedes Maybach", "V12");
console.log(mb2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fptnu8nnzak3w8qjqwdz8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fptnu8nnzak3w8qjqwdz8.png" alt="mb2 Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It only happens using the &lt;code&gt;function&lt;/code&gt; keyword using the Function Declaration approach. The arrow functions and function expressions cannot become a part-time object constructor.&lt;/p&gt;

&lt;p&gt;Furthermore, I will try to access the prototype of this object that I initiated through a constructor function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mb3 = new createBenz(
  "S-Class S680",
  "Mercedes Maybach",
  "V12"
);

createBenz.prototype.returnDetails = function () {
  console.log(
    `You are looking at ${this.brand}'s ${this.model} with a 
      ${this.engine} engine`
  );
};

createBenz.prototype.greetCustomer = function () {
  return `Welcome to Mercedes Benz 👋`;
};

console.log(mb3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrhy874g0s44l687x9zv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrhy874g0s44l687x9zv.png" alt="Updated mb2 Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The object prototype now holds the new &lt;code&gt;greetCustomer()&lt;/code&gt; and &lt;code&gt;returnDetails()&lt;/code&gt; method. It is how we can use Inheritance with objects. It marks one of the possibilities. I created another instance of &lt;code&gt;createBenz()&lt;/code&gt; without a class and inherited its methods and properties into an &lt;code&gt;m3&lt;/code&gt; object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mb4 = new createBenz(
  "C-Class C250",
  "Mercedes Benz",
  "2.2-liter BlueEfficiency"
);

createBenz.prototype.returnDetails = function () {
  console.log(
    `You are looking at ${this.brand}'s ${this.model} with a 
    ${this.engine} engine`
  );
};

createBenz.prototype.greetCustomer = function () {
  return `Welcome to Mercedes Benz 👋`;
};

console.log(mb3.returnDetails());
console.log(mb3.greetCustomer());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuewbu6yyyjdlib678ji.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuewbu6yyyjdlib678ji.png" alt="mb3 Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Prototypal Inheritance
&lt;/h2&gt;

&lt;p&gt;As I said before, objects are used alongside prototypes in JavaScript to achieve Inheritance. That is correct, and is called Prototypal Inheritance.&lt;/p&gt;

&lt;p&gt;Except for the extending class section, I demonstrated the examples of Prototypal Inheritance with the &lt;code&gt;porscheCar&lt;/code&gt; and &lt;code&gt;mercedesCar&lt;/code&gt; classes without telling you because, under the hood, JavaScript uses Prototypes, constructor functions as shown in the object-based inheritance sections, and objects themselves to perform Inheritance.&lt;/p&gt;

&lt;p&gt;It is by default Prototypal Inheritance even though it may appear as standard Inheritance using classes, but the reality hides behind objects.&lt;br&gt;
The concept of Classes in our context is sugarcoated. Those keywords from other languages allow us to add an abstraction layer on top of the actual functionalities of JavaScript.&lt;/p&gt;

&lt;p&gt;Those keywords, like &lt;code&gt;class&lt;/code&gt; and &lt;code&gt;constructor&lt;/code&gt;, are easier to read and write prototypes and Inheritance with objects. The syntax of Prototypes and objects is strange and baffling to understand.&lt;/p&gt;

&lt;p&gt;Hence, JS has a layer that covers Prototypal Inheritance and other concepts with keywords that seem relatable and relevant from other languages. They perform almost the same functionalities. However, they are different in JavaScript because of its design.&lt;/p&gt;

&lt;p&gt;The syntax to write Classes came in ES6 even though prototypes and objects controlled its functionalities. The keywords performed their job like in other languages to a standard developer.&lt;/p&gt;
&lt;h3&gt;
  
  
  Under the hood
&lt;/h3&gt;

&lt;p&gt;When you create the &lt;code&gt;porscheCar&lt;/code&gt; class, JavaScript creates a constructor function beneath the syntactic sugar. It initializes the desired properties and methods within the class prototype after building the &lt;code&gt;porscheCar&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creates the constructor function
function porscheCar() {}

// Creates the methods inside the Prototype
porscheCar.prototype.displayBrand = function () {
  console.log(`Brand: ${this.brand}`);
};

// Creates an Instance of the constructor
const car1 = new porscheCar();

// Creates the unique property for each object
car1.brand = "Porsche";

// Invokes the method through the Prototype
car1.displayBrand();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is — Brand: Porsche. The object-based Inheritance had a similar example. I used a standard function as a constructor function when I attached it with the &lt;code&gt;new&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;I created a new method inside the prototype of the constructor function. Each object will inherit this prototype with its method, such as &lt;code&gt;displayBrand()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;JavaScript creates properties with unique values for each object once an instance or object gets created. These are not a part of the prototype because I used the &lt;code&gt;this&lt;/code&gt; keyword, and that keyword always points to the owner object and not a class.&lt;/p&gt;

&lt;p&gt;The properties are for the object, so they remain unique. Further, they derive it from the constructor function Prototype when developers invoke its methods.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inheriting Properties VS Methods
&lt;/h2&gt;

&lt;p&gt;Allow me to explain this further. As I stated earlier, the properties and methods belong exclusively to the object because that is how the &lt;code&gt;this&lt;/code&gt; keyword works instead of focusing on the constructor function or the class.&lt;/p&gt;

&lt;p&gt;We directly attached the &lt;code&gt;displayBrand()&lt;/code&gt; method to the constructor function prototype. However, you can eliminate the default prototype behaviour by using the &lt;code&gt;this&lt;/code&gt; keyword while making the methods inside the class or constructor functions if you want these methods to stay exclusively unique for each object.&lt;/p&gt;

&lt;p&gt;I hate using constructor functions. Let me show the difference using a standard class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class atomicHabits {
  author = "James Clear";
  bookName = "Atomic Habits";

  constructor(rating, comments) {
    this.ratingOfBook = rating;
    this.extraComments = comments;

    this.displayProperties = function () {
      return `The ${this.bookName} book by ${this.author} has a rating of 
      ${this.ratingOfBook} and "${this.extraComments}" extra comment(s).`;
    };
  }
}

const reader1 = new atomicHabits("4.8", "N/A");
const reader2 = new atomicHabits("4.95", 
                                 "One of the best productivity books!");

console.log(atomicHabits);
console.log(reader1);
console.log(reader2);

console.log(reader1.displayProperties());
console.log(reader2.displayProperties());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;author&lt;/code&gt; and &lt;code&gt;bookName&lt;/code&gt; properties are outside the constructor because I don’t need input from the user about the book author and name.&lt;/p&gt;

&lt;p&gt;I have to attach the &lt;code&gt;displayProperties()&lt;/code&gt; method to each object without using the atomicHabit class prototype to make it unique for each object.&lt;/p&gt;

&lt;p&gt;We require a constructor, method, or accessor to use the &lt;code&gt;this&lt;/code&gt; keyword inside a class. I will avoid explaining getters and setters right now. Since I cannot use the &lt;code&gt;this&lt;/code&gt; keyword outside the constructor, I defined the &lt;code&gt;displayProperties()&lt;/code&gt; method using the &lt;code&gt;this&lt;/code&gt; keyword inside the constructor itself.&lt;/p&gt;

&lt;p&gt;Now, the method will convert into a property and get attached to each. And this is precisely the difference between properties and methods. You target each object individually using the &lt;code&gt;this&lt;/code&gt; keyword. Otherwise, you can define a function as a standard method each object inherits. You cannot modify it when the method is not an explicit property of the object.&lt;/p&gt;

&lt;p&gt;The author and bookName properties are not a part of the prototype but are unique to each object even without the &lt;code&gt;this&lt;/code&gt; keyword attached to them. I didn’t use the &lt;code&gt;this&lt;/code&gt; keyword because I am not creating and initializing it with a new value.&lt;/p&gt;

&lt;p&gt;However, the &lt;code&gt;displayProperties()&lt;/code&gt; function is now a property instead of a method. You can modify it for each object manually to perform different operations for various objects, and the properties remain changeable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F501u62r39uqvarnjgnqa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F501u62r39uqvarnjgnqa.png" alt="reader1 Output"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8wnf7h2jo9trzul3gybw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8wnf7h2jo9trzul3gybw.png" alt="reader2 Output"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;displayProperties()&lt;/code&gt; method is now a part of each object, and you can manually change it for one of the objects. Instead of inheriting the methods, these objects inherit them as properties. You can modify them now.&lt;/p&gt;

&lt;p&gt;It can also be a disadvantage. If you want to modify the method in multiple objects, you must alter them manually. It brings the second problem back. Hence, we only use them in specific scenarios and prefer prototypes in others.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reader1.displayProperties = function () {
  return `Changed without prototype! This will not change reader2 object!`;
};

console.log(reader1.displayProperties());
console.log(reader2.displayProperties());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I changed the method for the &lt;code&gt;reader1&lt;/code&gt; method without modifying the prototype and allowing the &lt;code&gt;reader2&lt;/code&gt; object to remain stable.&lt;/p&gt;

&lt;p&gt;The syntax and implementation seem like Java now. It means I should start packing my bags. See you, lads.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>What are taints and server actions in NextJS 14?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Tue, 28 Nov 2023 10:28:32 +0000</pubDate>
      <link>https://dev.to/whyafan/what-are-taints-and-server-actions-in-nextjs-14-1379</link>
      <guid>https://dev.to/whyafan/what-are-taints-and-server-actions-in-nextjs-14-1379</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;NextJS and its developers are prioritizing security. It’s time to understand the importance of data and the consequences. Most people are worried whether NextJS 14 will be problematic to implement.&lt;/p&gt;

&lt;p&gt;Many recently migrated to the 13th version that introduced the App Router, and people are worried whether this new update will cause them to switch again. However, experienced developers are stress-free.&lt;/p&gt;

&lt;p&gt;This release did not excite them. It did not prompt them to jump out of their chairs. The updates remained insignificant for some, and the lack of new APIs exhausted people. &lt;/p&gt;

&lt;p&gt;But that doesn’t indicate whether the release was utterly worthless. We have a few amusing features, and I will cover two of them in this article.&lt;/p&gt;

&lt;p&gt;Let’s understand &lt;strong&gt;Server Actions&lt;/strong&gt; and &lt;strong&gt;Taints&lt;/strong&gt;. I found people talking about them and insulting Server Actions, originally on Twitter. Later, I heard Theo talk about them in his videos referring to the NextJS Conf.&lt;/p&gt;

&lt;p&gt;So, naturally, I started to get into the rabbit hole of this new update, and here’s what I found.&lt;/p&gt;

&lt;h2&gt;
  
  
  Server Actions
&lt;/h2&gt;

&lt;p&gt;Server actions represent a function that allows you to write server-related code inside of code that looks like client code. Wait, WTF does that mean? It represents a set of actions inside a function that will run on the server but in a syntax that seems like you are writing client-side React components.&lt;/p&gt;

&lt;p&gt;Server actions are called straight from your React components. Vercel describes it as a function that runs securely on the server directly from your React components to avoid writing manual API routes or route handlers.&lt;/p&gt;

&lt;p&gt;NextJS is trying to add more security features to your codebases and applications. While server actions allow you to write code that will execute on the server, you can not put it inside client components because they avoid sending data to client devices while improving the developer experience. All of that is for security.&lt;/p&gt;

&lt;p&gt;You’re solely writing code that will execute on the server, like fetching data from a database, in a client-side fashion for simplicity and security reasons.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Page() {
  async function create(formData: FormData) {
    'use server';
    const id = await createItem(formData);
  }

  return (
    &amp;lt;form action={create}&amp;gt;
      &amp;lt;input type="text" name="name" /&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Take this code example from the documentation. For now, this code is secure because the JavaScript remains strictly on the server as we are using server actions.&lt;/p&gt;

&lt;p&gt;However, this code will breach the policies of server actions and the entire security tantrum if the code in the return statement remains visible to the user since it incorporates the information stored in a function outside that statement.&lt;/p&gt;

&lt;p&gt;Server Actions hide the information of those outside functions and only make the HTML visible to the client.&lt;/p&gt;

&lt;p&gt;The code snippet is a server component, and except for the &lt;code&gt;&amp;lt;form&amp;gt;&lt;/code&gt; HTML element, which will get sent to the client’s device, the entire JavaScript in the file remains in an imaginary vault and avoids exposing itself to the client.&lt;/p&gt;

&lt;p&gt;When the user clicks submit, the application pings a post request to the mentioned endpoint using ordinary web standards instead of AJAX, fetch, or anything remotely similar.&lt;/p&gt;

&lt;p&gt;Most people confuse back-end-related server action functions for APIs with the code inside the return statement defining the static front-end HTML markup because it is a JSX front-end file. However, JSX files and components are not client-side oriented anymore.&lt;/p&gt;

&lt;p&gt;It is something that the user will see, but the JavaScript will not get sent to the user. By the way, this is not a new concept either. &lt;/p&gt;

&lt;p&gt;Server actions have been around for quite a while now, and I’ve used them multiple times in my applications, but they are finally stable. There’s a significant difference in whether a code should get into production based on the status of the features and whether they are stable.&lt;/p&gt;

&lt;p&gt;Vercel deeply integrated Server actions with the App Router, which will help people using NextJS 13. You can redirect to different routes using the &lt;code&gt;redirect()&lt;/code&gt; method, set and read cookies using the &lt;code&gt;cookies()&lt;/code&gt; method, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Taints
&lt;/h2&gt;

&lt;p&gt;As I stated earlier, Vercel is prioritizing security. The name “Taint” is a ploy to attract more people towards this new concept that promotes security. However, simply put, it is an experimental feature in the form of an API that allows specific objects to avoid getting pushed to the client side.&lt;/p&gt;

&lt;p&gt;The rendering process of React begins with a plain HTML file with only a script tag. Then, it re-renders the empty HTML page and loads all the components with actual data, which is the process of hydration.&lt;/p&gt;

&lt;p&gt;During this loading phase, attributes get inserted into HTML elements dynamically. Some of these attributes are confidential. React and Next insert fields or private attributes inside HTML elements to identify which actions to execute and what context or data is required to run those actions.&lt;/p&gt;

&lt;p&gt;These actions could be fetching data from another source in the same application, getting data from a database, or working with an API. We don’t want our tokens to appear on HTML elements for server actions to operate appropriately. We want them hidden. We want them to be private. I don’t want my account to get hacked this easily. Therefore, taint exists.&lt;/p&gt;

&lt;p&gt;The basic idea is to avoid large objects accidentally getting exposed to the client. You can enable taint through the &lt;code&gt;next.config.js&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
module.exports = {
  experimental: {
    taint: true,
  },
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you can mark objects that should not get passed to the client side using the &lt;code&gt;experimental_taintObjectReference(message, object)&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { experimental_taintObjectReference } from 'react';

export async function getUserData(id) {
  const data = ...;
  experimental_taintObjectReference(
    'Do not pass user data to the client',
    data
  );
  return data;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The taint feature allows the returned values to remain secure. If trying to make files explicitly limited and only accessible on the server, not the client, we can use &lt;code&gt;import 'server-only';&lt;/code&gt; on the top of those files. It will not allow anyone to import those files and export its modules.&lt;/p&gt;

&lt;p&gt;If you try to import the &lt;code&gt;getUserData()&lt;/code&gt; function from the above code snippet into another file, you cannot use the object directly due to security concerns. The following code snippet will fail to execute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { getUserData } from './data';

export async function Page({ searchParams }) {
  const userData = getUserData(searchParams.id);
  return &amp;lt;ClientComponent user={userData} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, developers can still access and extract data fields from the object and pass them along.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function Page({ searchParams }) {
  const { name, phone } = getUserData(searchParams.id);
  // Intentionally exposing personal data
  return &amp;lt;ClientComponent name={name} phoneNumber={phone} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Intentially, we can expose the personal data to the client side by extracting those data fields and destructuring the object. &lt;/p&gt;

&lt;p&gt;The above code snippet will only extract the specific required data, like the name and phone number, while the rest remains untouched and sacred in an imaginary NextJS vault.&lt;/p&gt;

&lt;p&gt;Not only objects, but specific values, such as tokens, can also remain hidden from the client device using the &lt;code&gt;taintUniqueValue(errorMessage, object, value)&lt;/code&gt; call with an additional parameter. It is the value in strings, numbers, etc., after the object argument. However, taint cannot block derived values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { experimental_taintObjectReference, experimental_taintUniqueValue } from 'react';

export async function getUserData(id) {
  const data = ...;
  experimental_taintObjectReference(
    'Do not pass user data to the client',
    data
  );
  experimental_taintUniqueValue(
    'Do not pass tokens to the client',
    data,
    data.token
  );
  return data;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Taints can still get messy, and people can go over it. Instead of relying on them, you can combine taints as an additional layer of protection on top of something like a Data Access Layer.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Else?
&lt;/h2&gt;

&lt;p&gt;Don't get stressed about migrating your applications from NextJS 13 to 14. Most people will not use these new features, except the stable server actions, because we have been using them unknowingly for the longest time.&lt;/p&gt;

&lt;p&gt;It is simple to migrate and not necessary. The rest is on you. I will cover partial pre-rendering in a separate article. It is another new technique introduced in NextJS 14. They also spoke more about the NextJS Compiler with Turboback. It is their rust-based bundler for JS and TS.&lt;/p&gt;

&lt;p&gt;However, the compiler is unstable because it is not passing all the tests, so we will let developers smash their heads against it for a while. &lt;/p&gt;

&lt;p&gt;Nevertheless, Vercel also released React Learn, a course in the form of a book, trying to educate people about NextJS 13 and the basics of React to allow them to migrate from other languages effortlessly.&lt;/p&gt;

&lt;p&gt;Besides, uneducated people are also hating server actions for apparently reasons that arise from their lack of knowledge. In the NextJS Conf, the presenter displayed a slide explaining server actions with an open SQL statement using external values, like a slug, to use the insert statement for an SQL DB.&lt;/p&gt;

&lt;p&gt;However, the presenter used a specific in-built feature of TypeScript, which they did not cite in the slide, and that feature allows functions to be called using template literals and avoid the rest of the string. For more details on that feature, watch this.&lt;/p&gt;

&lt;p&gt;Until then.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>nextjs</category>
    </item>
    <item>
      <title>What are hooks in ReactJS?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Mon, 27 Nov 2023 12:15:02 +0000</pubDate>
      <link>https://dev.to/whyafan/what-are-hooks-in-reactjs-5ap6</link>
      <guid>https://dev.to/whyafan/what-are-hooks-in-reactjs-5ap6</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function. - &lt;em&gt;John Carmack. Oculus VR CTO.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When I started to learn React, I didn't read about its basic concepts. I directly jumped into writing React code because I found it trendy. However, not long into that journey, I faced the consequences of writing code without understanding its benefits.&lt;/p&gt;

&lt;p&gt;I finally understood what Ali Abdaal meant when he said, "&lt;strong&gt;&lt;em&gt;Learning and Practicing should be balanced together.&lt;/em&gt;&lt;/strong&gt;"&lt;/p&gt;

&lt;p&gt;Nonetheless, Hooks were one of the concepts that I had skipped theoretically. I knew how to write them and where to use them, but I wasn't aware of why we use them.&lt;/p&gt;

&lt;p&gt;I understood the intricacies of React Hooks, so you don't have to. I will help you learn what they are, why and how to use them in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Hooks?
&lt;/h2&gt;

&lt;p&gt;By definition, &lt;em&gt;hooks are functions in React that allow us to access and verify specific properties of UI elements, like their current state, without writing classes, constructors, etc.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hooks allow you to perform operations that Vanilla JS cannot&lt;/em&gt;. React has different built-in hooks - State Hooks, Context Hooks, Ref Hooks, Effect Hooks, etc.&lt;/p&gt;

&lt;p&gt;You are probably writing a hook in your code when you smash a random word with the &lt;code&gt;use&lt;/code&gt; keyword and call it a function that deconstructs an array into variables.&lt;/p&gt;

&lt;p&gt;Hooks uses features of the React framework, like SSR, to perform a specific task from within a component. However, the hooks do not live inside your React component.&lt;/p&gt;

&lt;p&gt;More often than not, these hooks perform basic operations, like trying to check the state of a UI element and whether the user interacted with it.&lt;/p&gt;

&lt;p&gt;Hooks allow us to use reusable states of components without changing their hierarchy. With hooks, developers can extract the current state of a UI element, grab DOM elements, and more independently and re-use those states and information in other components without creating extra classes, constructors, props, etc.&lt;/p&gt;

&lt;p&gt;We can also create custom hooks, which I will cover in a separate article, and for now, let us look at an example where hooks would be required. Then, we will understand why we need them and how to use them.&lt;/p&gt;

&lt;h3&gt;
  
  
  E-Commerce Example
&lt;/h3&gt;

&lt;p&gt;Consider yourself running an E-commerce brand. You have a page that displays your product with checkboxes to select the size, colour, etc. By default, the chosen choice is the first choice.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F782xc8hwxy8tvwoyhy1p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F782xc8hwxy8tvwoyhy1p.png" alt="Product Page Example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to check whether the user has selected a different choice, you require something directly into your component that verifies the current state of those selection boxes. A hook allows you to do that, specifically, the &lt;code&gt;useState()&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;Therefore, the &lt;code&gt;useState()&lt;/code&gt; hook returns the current state of UI elements and performs specific operations accordingly. These actions may include changing the product URL and attaching queries for the user to share.&lt;/p&gt;

&lt;p&gt;There are more hooks. If I want to select HTML elements from the DOM, I can use the &lt;code&gt;useRef()&lt;/code&gt; hook. If not using React, I would pick the elements with the &lt;code&gt;querySelector()&lt;/code&gt; method, etc.&lt;/p&gt;

&lt;p&gt;React hooks represent those operations that could work manually without a framework, but the complexity of frameworks wouldn't allow us to continue doing so. Thus, we efficiently implement those basic operations and insert additional benefits.&lt;/p&gt;

&lt;p&gt;Of course. Before hooks, developers accessed the state of UI elements and other details, but the downside of those features was writing extra code.&lt;/p&gt;

&lt;p&gt;Let's see why the React team introduced hooks and what developers used before them to access the states of UI elements.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use Hooks?
&lt;/h2&gt;

&lt;p&gt;Nowadays, websites aren't static. There are buttons, checkboxes, text input boxes, crazy animations, etc. A lot is going on at the same time. Developers require various techniques to keep up with these changes in the UI elements and manage them accordingly.&lt;/p&gt;

&lt;p&gt;They require various features in their choice of frameworks to swiftly grab user input, such as scrolling behaviour by writing less code. They want to select HTML elements, access their states, receive information from parent elements, etc.&lt;/p&gt;

&lt;p&gt;In those cases, we use hooks. Whenever there's a change, the &lt;code&gt;useState()&lt;/code&gt; hook keeps track of those changes and gets user input. Whenever you want to grab information from parent nodes and pass that information as props to child nodes, you can use &lt;code&gt;useContext()&lt;/code&gt;, and so on.&lt;/p&gt;

&lt;p&gt;However, if you think about it deeply, developers had to grab user input even before the React team introduced hooks. &lt;em&gt;React released Hooks in React 16.8 in early 2019&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So, what did developers use before 2019?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At that time, React implemented features in ways that most developers hated. &lt;em&gt;They forced front-end developers to use constructors inside classes with render props for the application to understand the current state of various UI components and use the data provided by the user to perform given actions&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Hooks allowed React developers to eradicate class-based components and directly render the UI with stateful logic and dynamic data from functional components. These functional components were not "&lt;em&gt;dumb components&lt;/em&gt;" anymore.&lt;/p&gt;

&lt;p&gt;The implementations of React class components were on the pure JavaScript syntax, and its Vanilla implementation inherited the disadvantages of JavaScript classes, including the excessive use of the &lt;code&gt;this&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;React didn't bother to create a class system either. They said they were not in the business of building a class system and further adopted the default system of JavaScript. All of these problems combined led to the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxp3bzve7zzbtie51u8mx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxp3bzve7zzbtie51u8mx.png" alt="FireShip Example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a small example of a class-based code snippet from Fireship trying to increment the count stored in a state wherein the user clicks on the button and displays the current count via an HTML element to the user.&lt;/p&gt;

&lt;p&gt;The classes and constructors before early 2019 started to give Java vibes. Back then, only React class components handled states and other DOM-based functionalities. The functional components were merely responsible for displaying information to the user through UI elements.&lt;/p&gt;

&lt;p&gt;Functional components till 16.8 received data in the form of props from parent components and precisely displayed them to the user. Developers hated React for that approach. So, React decided to introduce Hooks.&lt;/p&gt;

&lt;p&gt;Grabbing data from parent elements, attaining states, and other features were delegated to Hooks.&lt;/p&gt;

&lt;p&gt;Oh, and by the way, A state in React keeps track of how data changes in the application. It holds data in different forms that belong to a UI element. For example, it could store user input whenever the user types inside a textbox.&lt;/p&gt;

&lt;p&gt;Before Hooks, React was a mess compared to the advancements of today. Classes and constructors led to a wrapper hell. We had to pass a component into another component, and so on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fktectu8xakmcaya1wjkj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fktectu8xakmcaya1wjkj.png" alt="Wrapper Hell Example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Developers claimed frameworks provided seamless experience and faster performance.&lt;/p&gt;

&lt;p&gt;The entire idea of writing a class with other "yada yada" render props and high-order functionalities to solely check if a user selected a checkbox option contradicted their claim that frameworks were better than plain Vanilla JS.&lt;/p&gt;

&lt;p&gt;I wonder why Java developers found themselves inferior. So, the React team decided to step up their game. They introduced hooks that allowed us to access the state of UI elements through functions within React components without being in the same context of a framework.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use them?
&lt;/h2&gt;

&lt;p&gt;For starters, you cannot create hooks everywhere. You can only initialize them in the top level of a component. &lt;/p&gt;

&lt;p&gt;You cannot initiate them inside loops, conditionals, nested functions, etc. Otherwise, you can initialize them inside custom hooks strictly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./App.css";
import { useState } from "react"; // Import the hook

function App() {
  const [names, setName] = useState("Afan"); // Initialize the hook

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;p&amp;gt;{names}&amp;lt;/p&amp;gt;

      &amp;lt;input
        type="text"
        placeholder="Enter your name"
        onChange={(e) =&amp;gt; {
          setName(e.target.value);
        }}
      &amp;gt;&amp;lt;/input&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used the &lt;code&gt;useState()&lt;/code&gt; hook in this example. It keeps track of the current state of a UI element. When the state changes, we use the setter function provided by the second deconstructed array element named &lt;code&gt;setName()&lt;/code&gt; to set a new value to the first deconstructed value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A6kewMtVmSEaebzXm5Wmeew.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A6kewMtVmSEaebzXm5Wmeew.png" alt="Explanation by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;useState()&lt;/code&gt; hook simultaneously re-renders the UI element whenever the state of an element changes to update the UI elements using the data provided by a hook. The first variable in that hook array stores the data, and the second one is a setter used to collect the information from the UI element.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useState()&lt;/code&gt; solely accepts one optional parameter, which is the default value of the state. In other words, &lt;code&gt;Afan&lt;/code&gt; is the default value of the &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; tag and other UI elements using that hook to display values. This default value can be in strings, numbers, empty arrays &lt;code&gt;([])&lt;/code&gt;, empty objects &lt;code&gt;({})&lt;/code&gt;, etc.&lt;/p&gt;

&lt;p&gt;During the days of Classes and Constructors, objects represented the initial default value. Nonetheless, the brackets are required when initializing a hook. Those brackets represent the concept of Array Deconstruction.&lt;/p&gt;

&lt;p&gt;However, the variables inside those brackets aren't arrays. We can use multiple hooks in the same component. Mostly, we use &lt;code&gt;useState()&lt;/code&gt; to keep track of the user input through a form. Forms contain more than one field. Hence, we can initialize multiple hooks with different variable names and initial values at the beginning of the component function itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8c3yb30vdgdes3e2kqy6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8c3yb30vdgdes3e2kqy6.gif" alt="Output GIF 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similarly, you can initialize other hooks. All components using the same hook in the same file are also re-rendered whenever the state of that UI element changes.&lt;/p&gt;

&lt;p&gt;Every component that uses the data stored in the state will get re-rendered along with the entire page. React will modify and update those components together. Developers will not manually select each HTML element. Instead, React with its Babel will do that for us to update those components.&lt;/p&gt;

&lt;p&gt;Furthermore, hooks are asynchronous. If you try to call them multiple times, they will only re-render the component once in specific scenarios.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./App.css";
import { useState } from "react";

function App() {
  const [names, setName] = useState("Afan");

  function updateP(e) {
    setName(e.target.value + "HEY");
    setName(e.target.value + "HELLO");
    setName(e.target.value + "HOWDY"); // Only this setter function called
  }

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;p&amp;gt;{names}&amp;lt;/p&amp;gt;

      &amp;lt;input
        type="text"
        placeholder="Enter your name"
        onChange={(e) =&amp;gt; updateP(e)}
      &amp;gt;&amp;lt;/input&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I created the &lt;code&gt;updateP()&lt;/code&gt; function inside the main &lt;code&gt;App()&lt;/code&gt; function component and called the hook from that function. I invoked it three times, but only the last one executed and appended HOWDY to the modified string when it re-rendered.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fumrkbcan5ucwa5myaui2.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fumrkbcan5ucwa5myaui2.gif" alt="Output GIF 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I earlier claimed that hooks cannot reside inside functions, loops, etc. So, how the heck am I using them here? Well, you can invoke the setter function of the hooks inside functions, but you cannot create hooks inside functions.&lt;/p&gt;

&lt;p&gt;You can only create them at the top level of the component function. However, if you want the current string value to get appended with the previous value and invoke the setter function three times synchronously, you can use a callback function inside it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./App.css";
import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  function updateP() {
    setCount((prev) =&amp;gt; prev + 1);
    setCount((prev) =&amp;gt; prev + 1);
    setCount((prev) =&amp;gt; prev + 1);
  }

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;p&amp;gt;{count}&amp;lt;/p&amp;gt;

      &amp;lt;button onClick={updateP}&amp;gt;Increase&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example uses the default value provided in the hook. When the user clicks the button, the function &lt;code&gt;updateP()&lt;/code&gt; gets invoked, and the count changes.&lt;/p&gt;

&lt;p&gt;Since I passed a default value present inside the &lt;code&gt;useState()&lt;/code&gt; hook, those setter functions can use them and keep updating the previous value when I pass them as parameters.&lt;/p&gt;

&lt;p&gt;Inside the button, the function call doesn't require parenthesis. Otherwise, the entire application will enter an infinite loop of function calls. If the parenthesis is attached, the function will get invoked directly before the user clicks the button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx72k2vs7ui6ikqdg03m6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx72k2vs7ui6ikqdg03m6.gif" alt="Output GIF 3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In reality, the hook data lives outside the component that renders it. It is one level outside the component. Even without the respective context, hooks allow us to access that data and restrict its usage if it is confidential since it resides outside the component.&lt;/p&gt;

&lt;p&gt;Whenever the state of the component changes, React re-renders the entire page and delivers the data by storing it in the first array element of the &lt;code&gt;useState()&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Also, there's no strict rule about writing the names of the variables deconstructed from hooks. We use the keyword &lt;code&gt;set&lt;/code&gt; for the setter function because it is easier for other developers and ourselves to understand.&lt;/p&gt;

&lt;p&gt;Furthermore, we usually define those variables in combination. So, trying to get the first and last name of the user, the hook will have &lt;code&gt;[firstName, setFirstName]&lt;/code&gt;, &lt;code&gt;[lastName, setLastName]&lt;/code&gt;, etc. &lt;/p&gt;

&lt;p&gt;It is simply a convention commonly used by React developers while writing hooks to make them easily readable and understandable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Without Hooks and Constructors
&lt;/h2&gt;

&lt;p&gt;We understand that React recently introduced hooks in early 2019. Before that, developers used Classes and Constructors. Java developers felt inferior.&lt;/p&gt;

&lt;p&gt;However, some will argue that we don't require constructors or hooks to take user input from UI elements and display them. We can do it directly instead. For that, let's consider a click counter-example.&lt;/p&gt;

&lt;p&gt;I will try to directly update the values of a counter by storing them inside a variable, updating them whenever the user interacts with the component, and displaying the updated value to the user.&lt;/p&gt;

&lt;p&gt;I will exhibit the counter variable inside the &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; tag, and whenever I click on the button, it will update the UI element with the new incremented counter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./App.css";

function App() {
  let counter = 5;

  function updateP() {
    counter++;
    console.log(counter);
  }

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;p&amp;gt;{counter}&amp;lt;/p&amp;gt;

      &amp;lt;button onClick={updateP}&amp;gt;Increase&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, when you try to display the new updated value to the user during their interaction with your UI elements, the count variable will get the updated value, not the component.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fykk5t6h2kchov9w83g04.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fykk5t6h2kchov9w83g04.gif" alt="Output GIF 4"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The counter updates inside the variable, but the UI will not update because we are not using any function forcing React to re-render the component with its new data. &lt;/p&gt;

&lt;p&gt;There should be a trigger that refreshes the component and paints the new values.&lt;/p&gt;

&lt;p&gt;When using hooks, React updates the variable with the data using the setter function, and developers access the updated data using the first element in the deconstructed array. &lt;/p&gt;

&lt;p&gt;They call the hook to grab the data from within the React components.&lt;/p&gt;

&lt;p&gt;However, both array elements are useless if React doesn't re-render the page. When the page re-renders, the new data gets displayed to the user. Since the setter functions in hooks trigger the components to re-render, the UI gets updated too.&lt;/p&gt;

&lt;p&gt;And that's why either hooks or classes are required. Only specific hooks, like &lt;code&gt;useState()&lt;/code&gt;, re-render the page. It is the most commonly used hooks in the majority of applications.&lt;/p&gt;

&lt;p&gt;Instead of manually selecting DOM elements, updating the variables of each component that uses the data, and writing that much code, hooks make our lives easier.&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Hooks are functions that developers can invoke or call from within React components. They can access specific information from UI elements, such as user input, grab HTML elements, provide context, etc.&lt;/p&gt;

&lt;p&gt;The information attained from UI elements is stored one level outside the React components but within the same exported function.&lt;/p&gt;

&lt;p&gt;Hooks allow developers to perform various operations that Vanilla JS will fail to perform. Mostly, we use specific hooks to keep track of the state of a UI element using the &lt;code&gt;useState()&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;useState()&lt;/code&gt; hook allows us to access the details provided by the user or perform actions based on the interactions from the user, like scrolling through an element or clicking a button.&lt;/p&gt;

&lt;p&gt;Before hooks, developers used Classes and Constructors. That approach required us to write more code. Therefore, the React team introduced Hooks. We cannot manually reciprocate the functionalities of these hooks, like the &lt;code&gt;useState()&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;If we try to replicate the behaviour of the &lt;code&gt;useState()&lt;/code&gt; hook and manually update variables, the UI elements will continue to remain the same and not update because hooks cause React to re-render the entire page while keeping track of the last stored values of UI elements and their states.&lt;/p&gt;

&lt;p&gt;Each hook has a unique proposition that solves a problem wherein Vanilla JS fails. Hooks take advantage of the features of the React framework.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;And that's it.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="//mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;. Otherwise, Twitter (X) is the easiest way to reach out - &lt;a href="https://twitter.com/justmrkhan" rel="noopener noreferrer"&gt;@justmrkhan&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Which programming language should I learn first?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Fri, 27 Oct 2023 13:58:19 +0000</pubDate>
      <link>https://dev.to/whyafan/which-programming-language-should-i-learn-first-1g9f</link>
      <guid>https://dev.to/whyafan/which-programming-language-should-i-learn-first-1g9f</guid>
      <description>&lt;p&gt;Scrap the title. It is the wrong question to ask. The real question should be the following.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In which tech field can I make the most impact and help solve problems by building projects? Is it Web Development? Is it App Development?&lt;/p&gt;

&lt;p&gt;If Web Development, which tools and languages can I use?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s answer these questions. I created different roadmaps for various fields, including Data Science. Let’s take a look at them one by one and understand the reality of Software Development.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Even though you may want to pick your first language easily, I recommend putting in some time because you don’t want to waste your time quickly switching to another language and then repeat the loop wherein you switch languages when you lose interest.&lt;/p&gt;

&lt;p&gt;The stakes are high. It will take hundreds of hours of practice to become good at a language, especially JS, Java, Ruby, C++, etc. You must select a set of languages, stick to them, and keep building applications using them before switching to another one.&lt;/p&gt;

&lt;p&gt;Consider whether people will pay to build something using a specific language. For instance, take JavaScript. It gets used universally everywhere. &lt;/p&gt;

&lt;p&gt;Hence, the market demands proficient and well-versed JavaScript developers. If you know JS, you can switch to any other high-level language.&lt;/p&gt;

&lt;p&gt;Consider parameters like the job market, long-term vision, easiness of learning, and other factors when choosing a language. Don’t pick languages like C as your first if you want an easy language. Before we begin, use the following webcomic for a quick sarcastic overview.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flxnboe3hxm6attn24gue.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flxnboe3hxm6attn24gue.png" alt="By Toggl"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Most colleges and universities teach low-level C, Java, Assembly, MATLAB, and C++ as introductory programming languages due to the confusion about whether Computer Science is an extension of Mathematics.&lt;/p&gt;

&lt;p&gt;They teach most low-level languages because they are closer to Maths. However, we tend to use high-level languages in the real world. What is the difference between them? Read &lt;a href="https://x.com/justmrkhan/status/1707376203978740108?s=20" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Learning Programming while picking the wrong language is like using a hammer for a screw. It slows down your progress and demotivates while the programmer doesn’t get jobs even after spending hours trying to learn to program.&lt;/p&gt;

&lt;p&gt;Unless you pick PHP as your first language, there’s always something to learn. You will attain valuable skills with any language, but some might not align with your interests and require you to learn something completely different.&lt;/p&gt;

&lt;p&gt;So. Which language and tools should you pick?!&lt;/p&gt;

&lt;h2&gt;
  
  
  Choosing Languages
&lt;/h2&gt;

&lt;p&gt;Don’t go based on the popularity of a language. For the past 11 years, JavaScript has dominated the market as the most-used language for various fields, and that is because every industry uses it. However, what if you want to get into Data Science? There JavaScript isn’t the ideal option.&lt;/p&gt;

&lt;p&gt;It is similar to human languages. If I want to go to Germany, I’ll learn their native German language. If I want to visit India, I will learn Hindi. And if I want to go to France, I will learn French respectively. Your choice depends on what you’re trying to make.&lt;/p&gt;

&lt;p&gt;For the same reason, I drew multiple roadmaps for you. Most of these fields choose JavaScript as their core language. It is worth prioritizing, but I will go over other technologies to give a broader view other than my personal opinion.&lt;/p&gt;

&lt;p&gt;Remember that learning a single language will NOT propel your career. You will require other tools, like Git, Github, AWS, etc. I have considered relevant languages and tools with current or future potential in the Job Market.&lt;/p&gt;

&lt;h3&gt;
  
  
  Web Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Ar9b6ww_pmKKfLfFc5731ug.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Ar9b6ww_pmKKfLfFc5731ug.png" alt="Web Development Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Most frameworks and libraries in the roadmap are based on JavaScript and can be implemented easily with it. So, it’s crucial to understand the basics of JavaScript. Another essential topic in HTML is DOM. It is one of the requirements to understand React.&lt;/p&gt;

&lt;p&gt;Learn those JS technologies after you get a substantial basic knowledge of JS. Even the experienced engineers at Google recommend engineers master the basic knowledge first and practice explaining their thought processes.&lt;/p&gt;

&lt;p&gt;Full-stack developers are a combination of front-end and back-end. They handle both sides. Front-end developers create those beautiful interfaces, but the back end makes those elements and components functional.&lt;/p&gt;

&lt;p&gt;Astro and Eleventy are efficiently used to make static websites. They are not suitable for website-based applications like Twitter. We would learn React and Next JS based on React for an application like Twitter or Twitch.&lt;/p&gt;

&lt;p&gt;SCSS is a pre-processor. It improves the CSS writing process, and TailwindCSS and other libraries with the “UI” suffix are component libraries and frameworks that provide pre-written CSS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Science — AI/ML
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Ag-CWxoPVkA8KnqbnlNAWMQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Ag-CWxoPVkA8KnqbnlNAWMQ.png" alt="Data Science Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are tons of concepts in Data Science. People prioritize maths, statistics, and linear algebra with probability to understand other data-related concepts. Python appears as the best solution to process data. In reality, it is significantly slow compared to JavaScript. Python has more libraries and additional Data Science and AI/ML features.&lt;/p&gt;

&lt;p&gt;Tensorflow is another library used to bring those maths concepts and coding together to create a solution for a problem. NLPs are crucial to understanding even outside Data Science. And Kaggle is like Leetcode with pre-processed data to train your robots.&lt;/p&gt;

&lt;p&gt;Data Structures and algorithms will never leave your bedside. You will learn them in Data Science as well. It’s not because they are useful but because they allow you to build a problem-solving curious mindset even though developers treat it like an enemy that only serves its purpose in interviews.&lt;/p&gt;

&lt;h3&gt;
  
  
  Blockchain Development — Web3, Smart Contracts, etc.
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AMNIjAsjnjL9XV7GmI-xiag.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AMNIjAsjnjL9XV7GmI-xiag.png" alt="Blockchain Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Who would have thought I would speak about blockchain? However, this concept fascinated me during the research phase. I learned everything and the process wherein the back end depends on various blockchains and smart contracts to process user details and information. They are secure. &lt;/p&gt;

&lt;p&gt;As the Web3 concept supports the view of anonymity, blockchain allows you to do it.&lt;/p&gt;

&lt;p&gt;The front-end or the interface for the user gets built using React and Smart Contracts based on those blockchain systems that handle the back-end with tons of data.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mobile Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AEQLwNcrgpPmysKg4ctVhnQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AEQLwNcrgpPmysKg4ctVhnQ.png" alt="Mobile Development Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since 1993, when IBM was digging around mobile development, there were fewer technologies to rely on. Nowadays, there are many. We divide them into pure Android, hybrid, which can create applications on every platform, including desktop, and IOS, which only has one language with more restrictions than the military strength of Costa Rica.&lt;/p&gt;

&lt;p&gt;Frameworks like React Native, Flutter, and Ionic convert the code written using a common language into applications other platforms can adopt. Using the write code for one platform, I can make desktop, web, and mobile applications with them.&lt;/p&gt;

&lt;p&gt;They are hybrid and all-in-one solutions. But Java and Kotlin are ONLY for Android development and cannot create a desktop replica with the same code, and the same goes for the Swift language of IOS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Desktop Development
&lt;/h3&gt;

&lt;p&gt;As stated earlier, frameworks like React Native and Flutter allow you to write code that transpiles to all platforms. Hence, if you’re making a mobile application, you are more likely to develop a desktop version of it, and you can do that with those frameworks without learning anything additional.&lt;/p&gt;

&lt;p&gt;However, if you want to make desktop applications exclusively, I have something for you besides Java because most features released by Oracle for Java are useless (Applets were a thing).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Aa9G4j7Os5DwCLovh7EaUCg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Aa9G4j7Os5DwCLovh7EaUCg.png" alt="Desktop Development Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A desktop application with HTML CSS JS?! Yes. It becomes easier for you to make desktop applications if you hold fundamental knowledge of all those core web-based technologies. You don’t require quirky Java or .NET pain.&lt;/p&gt;

&lt;p&gt;Most platforms, including &lt;strong&gt;Notion&lt;/strong&gt;, convert the web-based application code of their platforms into desktop code using frameworks like Electron. If you try to press a specific shortcut, you will get the Chrome Developer tools on your desktop app even though you are not using a browser, and that’s magic.&lt;/p&gt;

&lt;p&gt;Try pressing &lt;em&gt;CTRL + I&lt;/em&gt; on the desktop application of Notion, and you will get a tab to view the HTML elements on a darn desktop application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Game Development
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Af0rmA_S1wwBDawZULyN-Uw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2Af0rmA_S1wwBDawZULyN-Uw.png" alt="Mobile Development Roadmap by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Either C++ or C#. No negotiation. It is because these are the popular languages used in most popular engines. These engines provide drag-and-drop solutions for complex mathematical movements in various games.&lt;/p&gt;

&lt;p&gt;C++ and C# are extensions of C, the mother of all languages. However, I wouldn’t recommend learning C first. I don’t want you to give up on programming after three days of getting started. It depends on your learning pace.&lt;/p&gt;

&lt;p&gt;These fields are like different trains. You can either pick one and stick to it daily, or first experience a gist of destinations travelled by all the trains and then pick one to travel daily.&lt;/p&gt;

&lt;p&gt;Optimize for what fits your personality and goals. I like to try everything first, gain experience, and then pick one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exploring Coding
&lt;/h2&gt;

&lt;p&gt;JavaScript or Python are the perfect beginner-level languages because they are used in most fields and are easier to learn. Most companies use frameworks and subsets of JavaScript. You can travel to different places with JavaScript and switch trains whenever you want without buying a new pass.&lt;/p&gt;

&lt;p&gt;I’d recommend you pick a language that allows open-source contributions to improve the packages and libraries created using that language and make better projects for other developers. Companies like Oracle often sue various companies for attempting to expand Java beyond its current capabilities.&lt;/p&gt;

&lt;p&gt;JavaScript avoids such behaviour, and that’s why so many companies adopted JS &amp;amp; TS together. Java wanted to conquer the entire market. They came up with Applets and other features. None of them lasted, and only JavaScript dominated the space. It has a large and supportive community to help you out.&lt;/p&gt;

&lt;p&gt;I recommend starting with Web Development because it is the easiest to learn and gives a sense of fulfilment or progress when you see your code representing your vision on the Internet.&lt;/p&gt;

&lt;p&gt;It is also because Web development-related concepts, frameworks, and libraries are present in other fields, like Web3, Desktop Development, Mobile development, and even AI/ML.&lt;/p&gt;

&lt;p&gt;You will master the basics of JavaScript and use it in other fields as you expand. Learn one language deeply. I would not recommend joining a boot camp either because they teach multiple languages and tools concurrently with no real purpose. &lt;/p&gt;

&lt;p&gt;You end up in a vicious cycle. Instead, pick a specific field and become a master of it.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Any application that can be written in JavaScript, will eventually be written in JavaScript. — Jeff Atwood, the co-founder of StackOverflow.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You should prioritize C over JavaScript because C is a low-level language. It is closer to hardware than other languages if you are intellectually curious and want to learn more about computers.&lt;/p&gt;

&lt;p&gt;If you don’t know which one to pick, watch a few YouTube videos of people from those various fields and verify whether it is something you would want to do. If yes, double down. Otherwise, move on to the next one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But what next&lt;/strong&gt;? I decided to pick the Web Development route and learned the technologies through practice with trial and error. What can I do next?&lt;/p&gt;

&lt;h2&gt;
  
  
  How do you use these languages and tools?
&lt;/h2&gt;

&lt;p&gt;Begin by building projects. When you have the fundamentals cleared, you can start using them. I created a 4-step framework for building projects while learning new skills. Hence, I won’t delve deeper into this topic, and you can purchase the 20-page eBook on Gumroad with over 70+ downloads.&lt;/p&gt;


&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://afankhan.gumroad.com/l/build-to-solve-problems" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fhyoaugeufg0yfkipglxbszf2te60" height="auto" class="m-0"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://afankhan.gumroad.com/l/build-to-solve-problems" rel="noopener noreferrer" class="c-link"&gt;
          Build to solve problems —  A 4-step framework guide to build impactful projects, learn skills, and build a portfolio.
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          Resumes do not matter anymore. Most high-ticket clients look for skills and practical knowledge. The best way to showcase practical knowledge is by building projects. Not only experience, but you get to learn new skills as you progress in making your projects.A degree has only become a piece of paper that signifies you worked hard for four years continuously, and dedicated yourself to merely ONE priority because they want to check whether you would leave their company or stay loyal to them for years.But how do you make impactful projects? Colleges and universities don’t teach the steps to building projects and creating a collection of those projects called a portfolio.Do not worry. I will provide a four-step framework to build great projects repeatedly. These projects will become great by providing value or solving a solution. Experience, projects, and skills matter more than mere knowledge as AI advances to memorising internet data.AI can provide the same knowledge through the internet. There are many resources. However, AI cannot give answers to problems developed by experience. When you build projects, you understand how one module interacts with the other. You face common issues and bugs. Some of these get addressed publicly, while others remain inside the minds of the top 1% of professionals.I’ll help you become a part of the 1% of professionals across various industries. You can apply the framework to any field, especially Computer Science. Everybody suggests we make a portfolio to get clients, but nobody gives the steps or path.I will answer the following questions in this eBook —How can I build great projects that add value to others?How can I acquire skills that will help us build those projects?How to build a portfolio?How can I make a mindset shift of building projects first and learning with experience?Many people waste their time trying to learn skills before creating projects, but it is the opposite, as I uncovered in the eBook.This eBook is for you if —You are someone who wants to achieve financial freedom by creating a service-based business because clients require proof of work.You are an unemployed person looking for new opportunities as projects become the utmost priority of clients and recruiters.You are a beginner, especially in industries like Software Development and want to get a head start before others with elusive work experience.You are a college student who wants to upskill themselves because the curriculum supports rote learners, not problem solvers. You cannot become a problem-solver without making projects.As I uncover the beginning of my Computer Science and hackathon journeys, I will explain how I built projects that mattered and how you can do the same.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpublic-files.gumroad.com%2Fhd88vtri1kk5bpacr6ecjgr6uxd2"&gt;
        afankhan.gumroad.com
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Practising is only the first step. If you don’t use those skills and knowledge to build something, you are essentially the human version of ChatGPT who only knows to spit out answers but cannot create anything.&lt;/p&gt;

&lt;p&gt;Engineers solve computer science-related problems using coding and leverage Programming to make websites and products to solve real-world problems. They fix those problems by building or doing something. &lt;br&gt;
They use their wisdom and experience.&lt;/p&gt;

&lt;p&gt;If you don’t use what you know, you will forget it and further blame yourself for failing to remember it. You will enter an endless loop. Hence, build a project and show it to your friends and family. Web Development is reasonable for showing.&lt;/p&gt;

&lt;p&gt;Once you build many projects and have a portfolio, you can apply for jobs or establish a service-based business (freelancing business). You offer your skills to a company through a job or an individual client through freelancing. I chose the latter.&lt;/p&gt;

&lt;p&gt;Build something that helps solve a problem in your daily life. Do you require a to-do list with reminders, dates, and other functionalities? Build it. &lt;/p&gt;

&lt;p&gt;Is it a PNG to SVG converter? Build it. Without looking at tutorials and solely based on documentation or articles, you build the application and learn the skills required to create these applications while creating them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Competitive Programming
&lt;/h2&gt;

&lt;p&gt;You might have heard this term. What does it mean? When programmers avoid caring about building projects and want to win competitions and interviews based on mathematical, data structural and complex algorithmic knowledge.&lt;/p&gt;

&lt;p&gt;I wouldn’t pick this route because competitive programmers live their lives inside a CLI, the command line interface, and fail to build projects they can deploy and show to the world or their friends and family. They can’t construct something that helps other people.&lt;/p&gt;

&lt;p&gt;There are a few times when this type of programming helps, and that is during interviews. After the discussion, people usually don’t come back to these concepts. They enter the real world where companies build things rather than solve complex leetcode problems.&lt;/p&gt;

&lt;p&gt;I suggest focusing on the roadmap provided earlier and returning to competitive programming once in a while with your desired language. I’m a JavaScript guy, so I use JavaScript and partially Python or C++ to solve leetcode problems whenever I decide to ruin my life (sarcasm).&lt;/p&gt;

&lt;p&gt;Most prefer Java and Python for leetcode problems, interviews, and tough coding questions. However, I don’t remember when I last solved a leetcode problem. Even ChatGPT can do that. I focus on building projects and dislike competitive programming.&lt;/p&gt;

&lt;p&gt;It could be because I’m an entrepreneur and freelancer now. However, if you’re optimizing yourself for a job, you will require competitive programming once you get the fundamentals correct with your respective field from the flowchart.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Dunning-Kruger effect
&lt;/h2&gt;

&lt;p&gt;More often than not, you will experience this effect. You will feel confident when you begin, then realize there are many things to learn. After reaching the lowest point of depression, you will get yourself back together, make a plan, and execute it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqyk4z9uzw8rje8d48cxq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqyk4z9uzw8rje8d48cxq.png" alt="From Jason Culloo"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I used to watch at least five videos of JavaScript on Udemy every day without fail. If I had to stay in my college library to complete them, I would till 5:30 PM. And while I did this, I realized that I don’t and can’t know everything. There’s so much to learn in JavaScript. I lost confidence, but I got back up eventually when I realized even seniors make mistakes.&lt;/p&gt;

&lt;p&gt;Hence, I started to focus on the crucial fundamental concepts I could learn and were within my reach instead of setting unrealistic expectations of completing JavaScript in 2 months.&lt;/p&gt;

&lt;p&gt;I also focused on embarrassing myself to learn more. What would be the best way to embarrass yourself? Hackathons!&lt;/p&gt;

&lt;h3&gt;
  
  
  Hackathons
&lt;/h3&gt;

&lt;p&gt;Once I had completed that course on JavaScript, I felt significantly confident in building complex applications. Rather than creating a project, I participated in a hackathon with other random strangers. And then I realized — I know nothing.&lt;/p&gt;

&lt;p&gt;I came, revised all concepts, built more projects, and participated again with the wisdom and experience gained from those previous hackathons. I embarrassed myself, but I quickly entered a state of enlightenment.&lt;/p&gt;

&lt;p&gt;To become a problem solver and great developer, you must know the basics of your field. Look at the flowchart, pick a topic like JS, and begin getting your hands dirty. There’s always a solution for something. You only need to find it.&lt;/p&gt;

&lt;p&gt;The computer is never wrong. Stop taunting it for your mistakes. Grasp humility. There’s a lot to learn, and you cannot do everything. If there’s something you don’t know yet, use AI models or Google.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Become a problem-solver.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;. Otherwise, Twitter (X) is the easiest way to reach out - @justmrkhan.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>What are Hydration, CSR, and SSR in React and NextJS?</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Sun, 22 Oct 2023 12:56:36 +0000</pubDate>
      <link>https://dev.to/whyafan/what-are-hydration-csr-and-ssr-in-react-and-nextjs-4ken</link>
      <guid>https://dev.to/whyafan/what-are-hydration-csr-and-ssr-in-react-and-nextjs-4ken</guid>
      <description>&lt;p&gt;Most developers, including myself, were confused about the difference between CSR and SSR. We couldn’t understand Hydration and its basic principles. However, let me fix all that for you. And trust me, it is easy to understand.&lt;/p&gt;

&lt;p&gt;But there’s a requirement to learn Hydration. We must first understand client-side rendering (CSR) and server-side rendering (SSR). The concept of Hydration lies within the problems of CSR.&lt;/p&gt;




&lt;h4&gt;
  
  
  I launched a new free eBook!
&lt;/h4&gt;

&lt;p&gt;The eBook is a 4-step framework to build projects and learn skills that enable you to attain practical experience in your field and become a developer whom recruiters and clients cannot say "No" during the discovery call.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;a href="https://afankhan.gumroad.com/l/build-to-solve-problems" rel="noopener noreferrer"&gt;https://afankhan.gumroad.com/l/build-to-solve-problems&lt;/a&gt;
&lt;/h4&gt;




&lt;h2&gt;
  
  
  Client-Side Rendering
&lt;/h2&gt;

&lt;p&gt;CSR is a rendering method that renders the entire application on the client (the user’s browser), including the execution of huge JavaScript files instead of rendering specific pieces of code on the server that do not require user input and others on the client.&lt;/p&gt;

&lt;p&gt;When users visit our website, CSR renders an empty HTML document on their browser without any data because that’s how fundamentally React works. If you’ve used React, you would know that every HTML page gets combined into one root file, and that file looks something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;script src="/static/js/bundle.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This empty file gets returned to the client browser when there’s a request. Once the browser locates the bundled JS files in this HTML file, the browser begins executing and parsing that JavaScript code, which contains the HTML DOM elements to fill the empty root div. Till then, the user witnesses a blank page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fku7tddle2gx64u59a5qw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fku7tddle2gx64u59a5qw.png" alt="Client-Side Rendering Diagram by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The JavaScript code in the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag divides into chunks of code. These chunks slowly execute once the browser locates the JS code. In CSR, these chunks load together, while SSR loads specific static chunks beforehand for faster execution.&lt;/p&gt;

&lt;p&gt;The HTML div gets content to display to the user once the browser fetches the JavaScript code from the server to the client device. Within the initial stage and your source code, this root remains empty.&lt;/p&gt;

&lt;p&gt;The browser requires the JavaScript files to load the website because the actual data to show the UI interface with its components to the user is present in them. If the JS file is missing, the HTML file will remain empty.&lt;/p&gt;

&lt;p&gt;CSR usually takes a few seconds to render the JavaScript code on the client device. Till the rendering completes, users witness an empty white page. Only a few static components are pre-loaded.&lt;/p&gt;

&lt;p&gt;When we keep adding additional components, the rendering becomes slower. And on weak networks, it becomes a huge problem. Most people don’t have fast devices with strong ethernet WiFi.&lt;/p&gt;

&lt;p&gt;Once the rendering completes, the user can view the entire webpage as a SPA (Single-Page Application). SPA means that all your content is on a single HTML file.&lt;/p&gt;

&lt;p&gt;Now, who wants a blank screen? We want to show something to the user till the browser fetches the JavaScript code with the actual data. However, client-side rendering cannot do that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Server-side Rendering
&lt;/h2&gt;

&lt;p&gt;Instead of rendering the UI interface on the client device, SSR renders a specific chunk of static code on the server beforehand and ships it to the client till the time-consuming dynamic JavaScript code executes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxbsjvor7j1yhzu8m297q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxbsjvor7j1yhzu8m297q.png" alt="First Render of SSR Diagram by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It doesn’t execute static code on the client device. Instead, it only runs dynamic content on the client device with event listeners and components that require user input.&lt;/p&gt;

&lt;p&gt;It creates a basic layout on the server, sends it to the client, and then transfers the JavaScript code with actual data to replace the temporary one. It is like having someone with the same face as a proxy for a few minutes till the original person swaps them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkrput86ydo9iq0ld9zio.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkrput86ydo9iq0ld9zio.png" alt="Second Render SSR Diagram by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will not ship another HTML file to replace the existing one during the second render. JavaScript will provide the new dynamic DOM. React Hydration process will compare the DOM provided by the JS code through the second render with the first render and replace static placeholders with dynamic content.&lt;/p&gt;

&lt;p&gt;NextJS supports SSR, and React implements it using React Server Components. NextJS isn’t an innovation. It is a React-based framework that renders the entire application on the server instead of the client.&lt;/p&gt;

&lt;p&gt;The initial state of a SPA is static when using SSR with no event listeners or data from DBs, APIs, etc. Everything is static. The dynamic content gets loaded slowly. But hey! At least we don’t see a white or incomplete page.&lt;/p&gt;

&lt;p&gt;It makes the process slightly better for small applications and creates significant advantages for massive applications.&lt;/p&gt;

&lt;p&gt;But what the heck is Hydration?&lt;/p&gt;

&lt;h2&gt;
  
  
  Hydration
&lt;/h2&gt;

&lt;p&gt;SSR sends the static skeleton HTML file compiled on the server with temporary data and static information to the client once the client (user) requests to load the website from the server.&lt;/p&gt;

&lt;p&gt;After that, the browser fetches those JavaScript files with actual data, DOM components, and custom code to recompose or repaint the application with the desired dynamic requested information.&lt;/p&gt;

&lt;p&gt;The virtual DOM created by SSR to serve as a temporary page gets compared with the actual DOM when JS loads. It compares the previous HTML with the new HTML through the difference in DOM trees. &lt;/p&gt;

&lt;p&gt;The DOM structure of the temporary page remains the same as generated by the new DOM but with actual data now. We can demonstrate this through the YouTube website.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fopf8yj2lx8dmfq0xqxs1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fopf8yj2lx8dmfq0xqxs1.png" alt="Youtube First Render through SSR"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The image represents the static temporary page. Once the browser gets the JS code, it executes, rebuilds the application, registers event listeners, and restores app states. &lt;/p&gt;

&lt;p&gt;The process between the rendering and comparison of the real DOM with the temporary DOM during the first render is the Hydration process.&lt;/p&gt;

&lt;p&gt;Once the rebuilding process is completed, the application enters the “Hydrated” state. This state includes comparing and initialising the new DOM nodes with authentic data. Hydration makes the application fully interactive with dynamic information. It happens at build-time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjsdooui5ji5gmqsbci78.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjsdooui5ji5gmqsbci78.png" alt="Youtube Second Render"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;YouTube is now hydrated. The original DOM tree from the first render doesn’t get changed. Instead, React combines the original one with the new DOM tree generated after understanding the JavaScript code and adopts the existing DOM.&lt;/p&gt;

&lt;p&gt;The rendering occurs two times in SSR, while the same doesn’t happen in CSR because the original data reaches the client on the first try and takes ample time to load it till the user clicks off.&lt;/p&gt;

&lt;h3&gt;
  
  
  Hydration isn’t perfect
&lt;/h3&gt;

&lt;p&gt;Hydration has its cons. The time between the second render and the first makes a significant difference. During this gap, the user cannot interact with dynamic components requiring factual data from the servers. It is called first interaction/interactivity.&lt;/p&gt;

&lt;p&gt;React tries to solve this by using Suspense and Streaming with ranking systems based on what the user wants to interact with. This time gap is called the Uncanny Valley. Hydration manages the gap between CSR and SSR, and this assumed valley.&lt;/p&gt;

&lt;p&gt;Even with SSR, the user must wait for the JS to re-load the temporary HTML and bring authentic data while they sit and stare at a default landing page with suspense-based cards. It depends on which route you would like to pick.&lt;/p&gt;

&lt;p&gt;Most chunks of websites and applications are static. Hence, these static components get rendered with temporary data on the server way ahead of time. They get built at compile-time by generating the initial HTML file.&lt;/p&gt;

&lt;p&gt;During Hydration, React or Next assumes that the DOM structure will match between both renders. During the first render, React builds a mental model of the future DOM and then constructs the future DOM using the JavaScript code in the second render.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Cereal Example
&lt;/h2&gt;

&lt;p&gt;Most cereal packets and boxes don’t have their expiry date printed during the box manufacturing. Heck, the cereal doesn’t even exist when the box gets manufactured.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Awp-PvNVo06vjozHV8_Cf2Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Awp-PvNVo06vjozHV8_Cf2Q.png" alt="The Cereal Example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hence, companies only print the standard design on the boxes, including the logo, an illustration, pictures, ingredient information, and a small space for the expiry date.&lt;/p&gt;

&lt;p&gt;A machine prints the expiry date on the boxes once the cereal production is completed, and the boxes get filled with them. Those boxes have many empty spaces because they do not have the actual content till production.&lt;/p&gt;

&lt;p&gt;In the same way, SSR (or two-pass rendering-based) applications are empty at the beginning. They only have the essential information shown to the user. In our case, this gets displayed through the temporary page with loading cards, buttons, etc.&lt;/p&gt;

&lt;p&gt;Once the data and content get fetched from JavaScript, the application starts to get filled with actual information. Then, users can interact with the dynamic content. The empty box gets filled with cereals. Our virtual DOM adapts the data from the real DOM through JavaScript.&lt;/p&gt;

&lt;h1&gt;
  
  
  Summary
&lt;/h1&gt;

&lt;p&gt;In a nutshell, SSR is the process of rendering a dummy loading page of an application on the server and shipping it to the user before loading the huge JavaScript files containing dynamic data that stop the execution of other files.&lt;/p&gt;

&lt;p&gt;Once this sample page gets loaded, the server sends the remaining JavaScript files that consume ample time to execute and allows the browser to begin parsing them while the user witnesses a static page. &lt;/p&gt;

&lt;p&gt;Based on the data and code from those JavaScript files, the browser re-renders the entire application with the actual data.&lt;/p&gt;

&lt;p&gt;Applications created using React and Next JS are SPA-based. It means that these applications combine into one HTML file. And this root HTML file gets displayed to the user.&lt;/p&gt;

&lt;p&gt;The other pages, including the main page, are handled using routes, but the root file holds the content for everything as it is the file that gets hydrated. &lt;/p&gt;

&lt;p&gt;Hydration is the process of re-rendering the dummy page with actual data. The root file is only sent once and modified later in the second render.&lt;/p&gt;

&lt;p&gt;We hydrate those pages. React has a component called Suspense. This component allows websites to provide a temporary page with the sample UI interface till the browser loads the actual JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb11awf9ufk2wydd0djg5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb11awf9ufk2wydd0djg5.png" alt="Image from Next JS Documents about Suspense and Streaming."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It allows selective components to get hydrated earlier while de-ranking others. If the user clicks on a specific component, that component gets the priority. &lt;/p&gt;




&lt;p&gt;If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at &lt;a href="mailto:hello@afankhan.com"&gt;hello@afankhan.com&lt;/a&gt;. Otherwise, Twitter (X) is the easiest way to reach out - @justmrkhan.&lt;/p&gt;

&lt;p&gt;I'd love to get your feedback through the comments section.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>Event Propagation &amp; Delegation: Bubbling and Capturing in JavaScript DOM</title>
      <dc:creator>Afan Khan</dc:creator>
      <pubDate>Sat, 14 Oct 2023 09:15:34 +0000</pubDate>
      <link>https://dev.to/whyafan/event-propagation-delegation-bubbling-and-capturing-in-javascript-dom-3616</link>
      <guid>https://dev.to/whyafan/event-propagation-delegation-bubbling-and-capturing-in-javascript-dom-3616</guid>
      <description>&lt;p&gt;JavaScript DOM events have specific phases, from clicking an element on a website to the JavaScript responding with a surprise. Most developers don't know how the browser handles events in its engine with the &lt;strong&gt;&lt;a href="https://medium.com/javascript-in-plain-english/what-is-dom-how-to-use-it-d13dbac43aec" rel="noopener noreferrer"&gt;DOM tree&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;If taken advantage of, they can reduce multiple LoC and efforts of the developer alongside the client-side browser. Only a few people are aware of these techniques. You can be one of them.&lt;/p&gt;




&lt;h4&gt;
  
  
  I launched a new free eBook!
&lt;/h4&gt;

&lt;p&gt;The eBook is a 4-step framework to build projects and learn skills that enable you to attain practical experience in your field and become a developer whom recruiters and clients cannot say "No" during the discovery call.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://afankhan.gumroad.com/l/build-to-solve-problems" rel="noopener noreferrer"&gt;Click here to get your copy&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Capturing &amp;amp; Target Phase
&lt;/h2&gt;

&lt;p&gt;We will use the following HTML code during this article.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Event Propogation and Delegation&amp;lt;/title&amp;gt;

    &amp;lt;link rel="stylesheet" href="styles.css" /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;section class="main"&amp;gt;
      &amp;lt;p class="main-p"&amp;gt;Click here 1&amp;lt;/p&amp;gt;
      &amp;lt;p class="main-p"&amp;gt;Click here 2&amp;lt;/p&amp;gt;
      &amp;lt;p class="main-p"&amp;gt;Click here 3&amp;lt;/p&amp;gt;
    &amp;lt;/section&amp;gt;

    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What do you expect the DOM to do when you click on one of those &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; elements? It creates a click event! However, the click event does not occur directly on the target element or the &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; tag. The actual event gets generated at the root of the HTML document. The Document object represents the root.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftsea70pgvcr4re97exty.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftsea70pgvcr4re97exty.gif" alt="GIF Animation demonstrating the Capturing Phase by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is the Capturing Phase. The click event object travels from the root of the DOM tree to the target element. It touches each parent element in the DOM tree before reaching its target during leisure travel because it gets generated at the root. The target phase begins when the event object arrives at the target element.&lt;/p&gt;

&lt;p&gt;During the target phase, the event handler executes the callback function on the target element after the object reaches the target element.&lt;/p&gt;

&lt;p&gt;These event handlers or listeners wait for specific events to occur on particular elements of the HTML DOM tree, and they react once that happens with a callback function alongside the default event object.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bubbling Phase
&lt;/h2&gt;

&lt;p&gt;In the bubbling phase, the event object returns to the document root after the execution of the callback function. The event comes from the root and returns to the root.&lt;/p&gt;

&lt;p&gt;Most developers leverage this bubbling phase to attach event listeners to parent elements instead of multiple child elements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0jzteyflyjx81osw4c55.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0jzteyflyjx81osw4c55.gif" alt="GIF Animation demonstrating the Bubbling Phase by Afan Khan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The events bubble up from the target to the document root element. The event passes through each parent element, not through any sibling elements, during its reincarnation to the root.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cool, but how the heck is this beneficial?
&lt;/h2&gt;

&lt;p&gt;It becomes beneficial because the Bubbling and Capturing phases allow events to pass through their parent elements. If we attach event listeners to parent elements instead of the target elements (child elements), we can perform the same operation with fewer LoC. These events precisely propagate from one end to another.&lt;/p&gt;

&lt;p&gt;Before reading this article, you used a forEach loop to iterate through each element of a specific class and attached event listeners to all of them, as shown in the following example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pTag = document.querySelectorAll(".main-p");

pTag.forEach((element) =&amp;gt; {
  element.addEventListener("click", () =&amp;gt; {
    element.classList.toggle("p-color-change");
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvplwksfye4c2twpaa2mv.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvplwksfye4c2twpaa2mv.gif" alt="Code Snippet Output - Without Bubbling"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But this is not viable. The loop takes ample time, and adding event listeners to all elements is inefficient. Therefore, we directly attach it to the parent element. In our case, the parent element is the &lt;code&gt;&amp;lt;section&amp;gt;&lt;/code&gt; tag.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const section = document.querySelector(".main");

section.addEventListener("click", (e) =&amp;gt; {
  const target = e.target;

  if (target.classList.contains("main-p")) {
    target.classList.toggle("p-color-change");
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As stated earlier, each event creates an object with many intricate details. Even the click event generates a click object that you can use by passing it as the first argument to the callback function of the event listener.&lt;/p&gt;

&lt;p&gt;The target property within the event object returns the HTML element that experienced the event. I am storing that HTML element in a variable for later use. After that, I verify whether the target element is my &lt;/p&gt;
&lt;p&gt; tag with a specific class. If yes, it will change the colour. Otherwise, it will ignore it.&lt;/p&gt;

&lt;p&gt;The if-statements are required because we attached the event listener to the parent element. There may be other elements in that parent element. I want the colour to change for any element except the &lt;/p&gt;
&lt;p&gt; tag. Hence, I require the if-statement.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4lnec3wptefuva2namex.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4lnec3wptefuva2namex.gif" alt="Output with Bubbling"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We achieved the same outcome with more efficiency. If you noticed, we use the Event object as a parameter to the callback function in the &lt;code&gt;addEventListener()&lt;/code&gt; method. This object contains the properties of a specific event and travels to the target element.&lt;/p&gt;

&lt;p&gt;Otherwise, you would attach an event listener to each parent element for the same callback function. You can directly connect the event listener to the parent element. The event object travels from the bottom to the top and vice versa as if the event had occurred on those elements instead of the target element.&lt;/p&gt;

&lt;p&gt;We can take leverage of this behaviour. Events can only be handled in the target and bubbling phases by default. But we can also set up a different approach to operate event listeners in the capturing phase with an extra parameter in the &lt;code&gt;addEventListener()&lt;/code&gt; method. However, we avoid doing that and prefer the Bubbling technique, as shown in the code snippet above.&lt;/p&gt;

&lt;p&gt;By the way, some events can't have Capturing and Bubbling phases. They directly opt for the target phase. However, most of the events must use the Capturing and Bubbling technique. If you notice that an event acts suspiciously to this approach, it could be because it is not supported yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;This was the process of Event Delegation because we were delegating the responsibility of the event listeners from the child elements to the parent elements with the concepts of Event Propagation.&lt;/p&gt;

&lt;p&gt;You can also perform Event Propagation without delegation, but I only do that to explain alternative solutions to students. We can add a third boolean parameter to &lt;code&gt;addEventListener()&lt;/code&gt; if we want them to invoke the callback functions during the capturing phase instead of the bubbling phase. By default, it is set to false as developers prefer using Bubbling.&lt;/p&gt;

&lt;p&gt;Bubbling and Capturing are here because of historical reasons when different browsers implemented identical, but not the same, versions of JavaScript. It was before ECMA Specifications.&lt;/p&gt;

&lt;p&gt;To summarize, the Event Propagation process has three different phases — Capturing, Bubbling, and Target. Each of these phases appears at the different DOM event reaction stages. They allow us to effectively apply event listeners to multiple elements concurrently without the requirement of loops and 100s of listeners.&lt;/p&gt;

</description>
      <category>dom</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
