<?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: Sam aghapour</title>
    <description>The latest articles on DEV Community by Sam aghapour (@samaghapour).</description>
    <link>https://dev.to/samaghapour</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%2F703806%2F880c3328-4c0d-4d27-96dc-ec13f1178f12.png</url>
      <title>DEV Community: Sam aghapour</title>
      <link>https://dev.to/samaghapour</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/samaghapour"/>
    <language>en</language>
    <item>
      <title>SOLID Principles in React: The Key to Writing Maintainable Components</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sat, 28 Sep 2024 15:02:46 +0000</pubDate>
      <link>https://dev.to/samaghapour/solid-principles-in-react-the-key-to-writing-maintainable-components-7bl</link>
      <guid>https://dev.to/samaghapour/solid-principles-in-react-the-key-to-writing-maintainable-components-7bl</guid>
      <description>&lt;p&gt;As React applications grow, things can get messy fast—bloated components, hard-to-maintain code, and unexpected bugs. That’s where the SOLID principles come in handy. Originally developed for object-oriented programming, these principles help you write clean, flexible, and scalable code. In this article, I’ll break down each SOLID principle and show how you can use them in React to keep your components organized, your code easier to maintain, and your app ready to grow.&lt;/p&gt;

&lt;p&gt;SOLID is an acronym that stands for five design principles aimed at writing clean, maintainable, and scalable code, originally for object-oriented programming but also applicable in React:&lt;/p&gt;

&lt;p&gt;S: &lt;strong&gt;Single Responsibility Principle&lt;/strong&gt;: Components should have &lt;strong&gt;one job or responsibility&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;O: &lt;strong&gt;Open/Closed Principle&lt;/strong&gt;: components should be &lt;strong&gt;open for extension **(easily enhanced or customized) but **closed for modification&lt;/strong&gt; (their core code shouldn't need changes).&lt;/p&gt;

&lt;p&gt;L: &lt;strong&gt;Liskov Substitution Principle&lt;/strong&gt;: components should &lt;strong&gt;be replaceable by their child components&lt;/strong&gt; without breaking the app's behavior.&lt;/p&gt;

&lt;p&gt;I: &lt;strong&gt;Interface Segregation Principle&lt;/strong&gt;: Components should &lt;strong&gt;not be forced to depend&lt;/strong&gt; on unused functionality.&lt;/p&gt;

&lt;p&gt;D: &lt;strong&gt;Dependency Inversion Principle&lt;/strong&gt;: Components should &lt;strong&gt;depend on abstractions&lt;/strong&gt;, not concrete implementations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Single Responsibility Principle (SRP)
&lt;/h2&gt;

&lt;p&gt;Think of it like this: Imagine you have a toy robot that can only do one job, like walking. If you ask it to do a second thing, like talk, it gets confused because it's supposed to focus on walking! If you want another job, get a second robot.&lt;/p&gt;

&lt;p&gt;In React, a component should only do one thing. If it does too much, like fetching data, handling form inputs, and showing UI all at once, it gets messy and hard to manage.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserCard = () =&amp;gt; {
  const [user, setUser] = useState(null);

  useEffect(() =&amp;gt; {
    fetch('/api/user')
      .then(response =&amp;gt; response.json())
      .then(data =&amp;gt; setUser(data));
  }, []);

  return user ? ( &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt; ) : &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the UserCard is responsible for both fetching data and rendering the UI, which &lt;strong&gt;breaks the Single Responsibility Principle&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const useFetchUser = (fetchUser) =&amp;gt; {
  const [user, setUser] = useState(null);

  useEffect(() =&amp;gt; {
    fetchUser().then(setUser);
  }, [fetchUser]);

  return user;
};

const UserCard = ({ fetchUser }) =&amp;gt; {
  const user = useFetchUser(fetchUser);

  return user ? (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  ) : (
    &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the data fetching logic is moved to a custom hook (useFetchUser), while UserCard focuses solely on rendering the UI, and &lt;strong&gt;maintaining SRP&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Open/Closed Principle (OCP)
&lt;/h2&gt;

&lt;p&gt;Think of a video game character. You can add new skills to the character (extensions) without changing their core abilities (modifications). That’s what OCP is about—allowing your code to grow and adapt without altering what’s already there.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Alert = ({ type, message }) =&amp;gt; {
  if (type === 'success') {
    return &amp;lt;div className="alert-success"&amp;gt;{message}&amp;lt;/div&amp;gt;;
  }
  if (type === 'error') {
    return &amp;lt;div className="alert-error"&amp;gt;{message}&amp;lt;/div&amp;gt;;
  }
  return &amp;lt;div&amp;gt;{message}&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, every time you need a new alert type, you have to modify the Alert component, which breaks OCP. whenever you add conditional rendering or switch case rendering in your component, you are making that component less maintainable, cause you have to add more conditions in the feature and modify that component core code that breaks OCP.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Alert = ({ className, message }) =&amp;gt; (
  &amp;lt;div className={className}&amp;gt;{message}&amp;lt;/div&amp;gt;
);

const SuccessAlert = ({ message }) =&amp;gt; (
  &amp;lt;Alert className="alert-success" message={message} /&amp;gt;
);

const ErrorAlert = ({ message }) =&amp;gt; (
  &amp;lt;Alert className="alert-error" message={message} /&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the Alert component is &lt;strong&gt;open for extension&lt;/strong&gt; (by adding SuccessAlert, ErrorAlert, etc.) but &lt;strong&gt;closed for modification&lt;/strong&gt; because we don’t need to touch the core Alert component to add new alert types.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Want OCP? Prefer composition to inheritance&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Liskov Substitution Principle (LSP)
&lt;/h2&gt;

&lt;p&gt;Imagine you have a phone, and then you get a new smartphone. You expect to make calls on the smartphone just like you did with the regular phone. If the smartphone couldn’t make calls, it would be a bad replacement, right? That's what LSP is about—new or child components should work just like the original without breaking things.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Button = ({ onClick, children }) =&amp;gt; (
  &amp;lt;button onClick={onClick}&amp;gt;{children}&amp;lt;/button&amp;gt;
);

const IconButton = ({ onClick, icon }) =&amp;gt; (
  &amp;lt;Button onClick={onClick}&amp;gt;
    &amp;lt;i className={icon} /&amp;gt;
  &amp;lt;/Button&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, if you swap the Button with the IconButton, you lose the label, breaking the behavior and expectations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Button = ({ onClick, children }) =&amp;gt; (
  &amp;lt;button onClick={onClick}&amp;gt;{children}&amp;lt;/button&amp;gt;
);

const IconButton = ({ onClick, icon, label }) =&amp;gt; (
  &amp;lt;Button onClick={onClick}&amp;gt;
    &amp;lt;i className={icon} /&amp;gt; {label}
  &amp;lt;/Button&amp;gt;
);

// IconButton now behaves like Button, supporting both icon and label

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, IconButton properly extends Button's behavior, supporting both icons and labels, so you &lt;strong&gt;can swap them without breaking functionality&lt;/strong&gt;. This follows the Liskov Substitution Principle because the child (IconButton) can replace the parent (Button) without any surprises!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If B component extends A component, anywhere you use A component, you should be able to use B component.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Interface Segregation Principle (ISP)
&lt;/h2&gt;

&lt;p&gt;Imagine you’re using a remote control to watch TV. You only need a few buttons like power, volume, and channel. If the remote had tons of unnecessary buttons for a DVD player, radio, and lights, it would be annoying to use.&lt;/p&gt;

&lt;p&gt;Suppose you have a data table component that takes a lot of props, even if the component using it doesn’t need all of them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const DataTable = ({ data, sortable, filterable, exportable }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    {/* Table rendering */}
    {sortable &amp;amp;&amp;amp; &amp;lt;button&amp;gt;Sort&amp;lt;/button&amp;gt;}
    {filterable &amp;amp;&amp;amp; &amp;lt;input placeholder="Filter" /&amp;gt;}
    {exportable &amp;amp;&amp;amp; &amp;lt;button&amp;gt;Export&amp;lt;/button&amp;gt;}
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This component forces all consumers to think about sorting, filtering, and exporting—even if they only want a simple table.&lt;/p&gt;

&lt;p&gt;You can split the functionality into smaller components based on what’s needed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const DataTable = ({ data }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    {/* Table rendering */}
  &amp;lt;/div&amp;gt;
);

const SortableTable = ({ data }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;DataTable data={data} /&amp;gt;
    &amp;lt;button&amp;gt;Sort&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
);

const FilterableTable = ({ data }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;DataTable data={data} /&amp;gt;
    &amp;lt;input placeholder="Filter" /&amp;gt;
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, each table only includes the functionality that’s needed, and you’re not forcing unnecessary props everywhere. This follows ISP, where components &lt;strong&gt;only depend on the parts they need&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dependency Inversion Principle (DIP)
&lt;/h2&gt;

&lt;p&gt;Imagine you're building with LEGO blocks. You have a robot built with specific pieces. But what if you want to swap out its arms or legs? You shouldn't have to rebuild the whole thing—just swap out the parts. The Dependency Inversion Principle (DIP) is like this: your robot (high-level) doesn't depend on specific parts (low-level); it depends on pieces that you can change easily.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserComponent = () =&amp;gt; {
  useEffect(() =&amp;gt; {
    fetch('/api/user').then(...);
  }, []);
  return &amp;lt;div&amp;gt;...&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This directly depends on fetch—you can’t swap it easily.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserComponent = ({ fetchUser }) =&amp;gt; {
  useEffect(() =&amp;gt; {
    fetchUser().then(...);
  }, [fetchUser]);
  return &amp;lt;div&amp;gt;...&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the fetchUser function is passed in, and you can easily swap it with another implementation (e.g., mock API, or another data source), keeping everything flexible and testable.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Final Thoughts&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Understanding and applying SOLID principles in React can drastically improve the quality of your code. These principles—Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion—help you write components that are more modular, flexible, and easier to maintain. By breaking down responsibilities, keeping code extensible, and making sure each part of your app interacts in predictable ways, you can create React applications that scale more easily and are simpler to debug. In short, SOLID principles lead to cleaner and more maintainable codebases.&lt;/p&gt;

</description>
      <category>solid</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
    </item>
    <item>
      <title>Next.js Caching: Turbocharging Your App with Efficient Data Fetching</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Mon, 16 Sep 2024 08:23:33 +0000</pubDate>
      <link>https://dev.to/samaghapour/nextjs-caching-turbocharging-your-app-with-efficient-data-fetching-51hb</link>
      <guid>https://dev.to/samaghapour/nextjs-caching-turbocharging-your-app-with-efficient-data-fetching-51hb</guid>
      <description>&lt;p&gt;Caching in Next.js isn’t just about saving time—it’s about reducing redundant network requests, keeping data fresh, and making your app perform like a rockstar. &lt;br&gt;
Whether you’re trying to keep data cached for longer or refresh it on-demand, Next.js gives you all the tools you need. In this article, we will break down how to use caching effectively in Next.js&lt;/p&gt;

&lt;p&gt;Next.js extends the fetch API to give you superpowers when it comes to caching. With simple fetch options like &lt;strong&gt;cache: 'no-store'&lt;/strong&gt; and &lt;strong&gt;cache: 'force-cache'&lt;/strong&gt;, you can easily control when and how data is cached.&lt;/p&gt;
&lt;h3&gt;
  
  
  Always Fresh with cache: 'no-store' (Equivalent to unstable_noStore())
&lt;/h3&gt;

&lt;p&gt;Want fresh data every time? &lt;strong&gt;cache: 'no-store'&lt;/strong&gt; is the one to go with. This fetch option skips the cache entirely and grabs the latest data with every request. It’s perfect when you need real-time accuracy—no leftovers from yesterday's fetch allowed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F66z1g9uvqbfrqsk0do0u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F66z1g9uvqbfrqsk0do0u.png" alt="no-store" width="800" height="486"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: You can also use &lt;strong&gt;unstable_noStore()&lt;/strong&gt; if you want to skip the cache on a server component. The syntax may change later, so stick with &lt;strong&gt;cache: 'no-store'&lt;/strong&gt; for stability.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;
  
  
  Reuse Data with &lt;code&gt;cache: 'force-cache'&lt;/code&gt; (Equivalent to &lt;code&gt;unstable_cache()&lt;/code&gt;)
&lt;/h4&gt;

&lt;p&gt;On the other hand, if you’re okay with using cached data (think static content that doesn’t change often), go with &lt;strong&gt;cache: 'force-cache'&lt;/strong&gt;. It’ll save the response for future use and skip redundant network requests.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F2f3g381cx0qlvjqjh1rp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F2f3g381cx0qlvjqjh1rp.png" alt="force-cache" width="800" height="486"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: &lt;strong&gt;unstable_cache()&lt;/strong&gt; also caches data, but using the stable &lt;strong&gt;cache: 'force-cache'&lt;/strong&gt; is more reliable if you’re avoiding surprises down the road.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fwzxl3z9gl1cgwnkn30fw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fwzxl3z9gl1cgwnkn30fw.png" alt="Fetch options" width="800" height="328"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Keep It Fresh with Revalidations
&lt;/h3&gt;

&lt;p&gt;Sometimes cached data needs a refresh—whether it's after a certain time or when triggered by an event. Lucky for you, Next.js lets you revalidate your cached data in several ways.&lt;/p&gt;
&lt;h4&gt;
  
  
  Revalidate with Time: &lt;code&gt;next.revalidate&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;If your data needs to refresh periodically (like every hour or day), you can set a revalidation period using the &lt;strong&gt;next.revalidate&lt;/strong&gt; option in your fetch request. It’ll grab the latest data after the time you specify while keeping things cached the rest of the time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ff7j6j29thqksydisjbjt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ff7j6j29thqksydisjbjt.png" alt="Revalidate time" width="800" height="617"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://api.example.com/data', {
  next: { revalidate: 3600 }  // Revalidate data every hour (3600 seconds)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  On-Demand Revalidation with Tags: &lt;code&gt;revalidateTag()&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;Now, Imagine you can tell Next.js to refresh specific bits of cached data when something important happens—like a form submission or a new blog post going live. You can assign tags to your cached data, and then revalidate those tags whenever needed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ftt5o372i4p9v22tarx5x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ftt5o372i4p9v22tarx5x.png" alt="Revalidate tag" width="800" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fei0l8jfxhurs9mg4otoo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fei0l8jfxhurs9mg4otoo.png" alt="revalidateTag" width="800" height="468"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This way, you can manually refresh parts of your cache on demand without waiting for the next scheduled revalidation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using the Unstable Methods
&lt;/h3&gt;

&lt;p&gt;If you’re the adventurous type, you can also use the &lt;strong&gt;unstable_noStore()&lt;/strong&gt; and &lt;strong&gt;unstable_cache()&lt;/strong&gt; methods directly on server components to manage caching behavior. Just keep in mind, that these are "unstable" for a reason, so they might change in the future( or might have been changed at the time you are reading it).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F9rg7l8mlk8zi5ly5tsc3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F9rg7l8mlk8zi5ly5tsc3.png" alt="unstable_noStore" width="800" height="560"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Or if you’re into caching, here’s how you can use unstable_cache():&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fbc6zgyp6vlcen1js7gpo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fbc6zgyp6vlcen1js7gpo.png" alt="unstable_cache" width="800" height="776"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Skip the Prop Drilling
&lt;/h3&gt;

&lt;p&gt;Here’s a neat trick: if you’re fetching the same data across multiple components (like a Layout, Page, and some inner components), don’t stress about fetching it once at the top and passing it down or having to make a request for that data multiple times on multiple components that cause slowing down the performance. Next.js automatically memoizes fetch requests during server rendering, meaning if you fetch the same data multiple times, it’s smart enough to only hit the network once and share the result in multiple components.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fuikpvb01hes0xxfxpqn0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fuikpvb01hes0xxfxpqn0.png" alt="deduplicated fetch requests" width="800" height="424"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fpwpkmfxmmsiy5ovxcx5g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fpwpkmfxmmsiy5ovxcx5g.png" alt="Data memoization" width="800" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fo71o0j1i632b8lsr9bgf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fo71o0j1i632b8lsr9bgf.png" alt="Default caching" width="800" height="642"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Wrapping It Up
&lt;/h3&gt;

&lt;p&gt;Next.js gives you all the tools you need to manage caching effectively, whether through fetch API options like &lt;strong&gt;cache: 'no-store'&lt;/strong&gt; and &lt;strong&gt;cache: 'force-cache'&lt;/strong&gt;, or the more experimental unstable_noStore() and unstable_cache() methods. Add in revalidation strategies like &lt;strong&gt;next.revalidate&lt;/strong&gt; and &lt;strong&gt;revalidateTag&lt;/strong&gt;, and you’ve got everything you need to keep your data fresh without breaking a sweat.&lt;/p&gt;

&lt;p&gt;Sources:&lt;br&gt;
&lt;a href="https://nextjs.org/docs/app/building-your-application/caching" rel="noopener noreferrer"&gt;Next.js caching&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>nextjs</category>
      <category>react</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Everything You need to know about React 19</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 05 May 2024 13:52:01 +0000</pubDate>
      <link>https://dev.to/samaghapour/everything-you-need-to-know-about-react-19-4o97</link>
      <guid>https://dev.to/samaghapour/everything-you-need-to-know-about-react-19-4o97</guid>
      <description>&lt;p&gt;React 19 has been released with a series of new and exciting changes that we will cover in this post. These changes include new features, improvements, deprecations, or replacements of current features.&lt;/p&gt;

&lt;p&gt;Changes that enable us as software engineers to achieve more and better output with less code.&lt;/p&gt;

&lt;p&gt;We will discuss all the major changes mentioned below:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;React Compiler&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;forwardRef =&amp;gt; Ref as a prop&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Document Metadata&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Server Components&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Actions&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;New Hooks (use(), useFormStatus(), useOptimistic()&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  React Compiler
&lt;/h2&gt;

&lt;p&gt;One of the longstanding issues in React has been unnecessary re-renders, which can harm the performance of a project. It wasn't logical to re-render a component simply because its parent component had re-rendered when the props it received hadn't changed. Imagine having many nested components that didn't need to re-render because their props hadn't changed, but they did anyway because the parent component re-rendered, slowing down the website's speed.&lt;/p&gt;

&lt;p&gt;To solve this problem, the React team introduced techniques to allow us to memoize the data passed as props to prevent unnecessary re-renders.&lt;/p&gt;

&lt;p&gt;These techniques involved the use of useMemo, useCallback, and Memo.&lt;/p&gt;

&lt;p&gt;However, the issue with this approach is that many people don't know exactly when it's appropriate to use these techniques. Sometimes the re-render might not be worth it and could even worsen performance since these hooks involve a process of comparing previous props with new ones. (You can read more about this in an article I wrote about &lt;a href="https://dev.to/samaghapour/performance-optimization-tips-for-react-projects-4mj"&gt;improving the performance of React projects&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;Secondly, in my opinion, they don't provide a particularly interesting Developer Experience.&lt;/p&gt;

&lt;p&gt;After much feedback from the community and considerable time spent, the React team finally announced that they have been working on the React compiler and are currently using it on Instagram. They plan to release it in upcoming versions soon.&lt;/p&gt;

&lt;p&gt;This compiler will transform your React code into pure JavaScript and handle the performance improvement and memoization process behind the scenes, so you won't need to use those hooks any more.&lt;/p&gt;

&lt;p&gt;As a result, useCallback, useMemo, and memo will easily become redundant in React, simplifying our work.&lt;/p&gt;

&lt;h2&gt;
  
  
  ForwardRef =&amp;gt; Ref as a prop
&lt;/h2&gt;

&lt;p&gt;Previously, when we had a variable that was equal to useRef, and we wanted to pass this variable to a child component for use there, we would use forwardRef to be able to receive and use that passed ref in addition to the props, like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fju638nuwolrmkv9t30py.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fju638nuwolrmkv9t30py.jpeg" alt="forwardref" width="589" height="485"&gt;&lt;/a&gt;&lt;br&gt;
But now, there’s no need for that, and we can directly pass the ref as a prop, like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fogd98zm3llmw098l7opu.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fogd98zm3llmw098l7opu.jpeg" alt="ref" width="599" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thus, there is no need for forwardRef anymore.&lt;/p&gt;

&lt;h2&gt;
  
  
  Support for MetaData
&lt;/h2&gt;

&lt;p&gt;In previous versions of React, whenever we wanted to add tags to the head of a document within a JSX component, we were forced to use libraries like React Helmet. But now, we can directly place meta tags, link tags, and others that belong in the head within JSX. React will automatically detect them, extract them, and place them in the head tag, like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fzbmv6kom3kl37jlbiek3.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fzbmv6kom3kl37jlbiek3.jpeg" alt="MetaData" width="800" height="508"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Server Components
&lt;/h2&gt;

&lt;p&gt;The topic of server components and client components has been around for a while, and we use it extensively in Next.js.&lt;/p&gt;

&lt;p&gt;In general, server-side components are those that are built on the server side during the build process. By not being included in the JavaScript bundle, they reduce its size and improve performance. They also have several other advantages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;SEO Improvement: Server-side components are rendered on the server and returned as ready-made HTML, giving search engine crawlers access to more content, which improves SEO. In client-side code, since the components are built on the client and dynamically update the page content with JavaScript, initially, there is no content, and the page source is empty, so crawlers find nothing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance Improvement: As mentioned in the first point, since server-side components are built or pre-built on the server during the build process, they load very quickly, resulting in better performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Security: Server components allow sensitive data like tokens and API keys to remain on the server side and not be accessible on the client side, which increases the site's security.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These are the major advantages, and if we only consider these, React was missing out on significant benefits of server-side rendering in previous versions. However, in the recent version, React has added server components. Unlike Next.js, React components are still client-side by default, and if we want them to be server-side rendered, we must add a directive like this to the first line of our component:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;'use server';&lt;br&gt;
import React from 'react';&lt;br&gt;
...&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This directive tells React to render the component on the server side, leveraging the benefits of server-side rendering.&lt;/p&gt;

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

&lt;p&gt;Actions are a new feature in React that changes the way we handle forms. Previously, we relied on the submit button in the form and also needed states to access the values of the inputs within the form to submit the data. Now, with the use of the action attribute on the form tag, we can capture and submit the data in this manner:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F9oc1ijpf436oqx3klj48.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F9oc1ijpf436oqx3klj48.jpeg" alt="Actions" width="599" height="677"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, the action is set to a function that returns the data in the form, as the first parameter. We can use the get method it provides to retrieve the name of each input within the form and get the submitted value.&lt;/p&gt;

&lt;p&gt;In the next section, I’ll introduce new hooks that have been added, and we’ll see even more improvements in handling forms.&lt;/p&gt;

&lt;h2&gt;
  
  
  UseFormState and useFormStatus
&lt;/h2&gt;

&lt;p&gt;These two new hooks have been added to React to make working with forms easier for us.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useFormState()&lt;/strong&gt;: &lt;br&gt;
This hook allows us to have a state and set the value of that state based on the result returned in the form action handler. Let’s see an example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fpnt8dr6r7lzxczwxsxqk.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fpnt8dr6r7lzxczwxsxqk.jpeg" alt="before useFormState" width="800" height="584"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code above is a scenario where the action and the useFormState hook have not been used, and we see that three inputs are defined for the inputs and the message that returns from our request.&lt;/p&gt;

&lt;p&gt;Now, let’s write the same using the action and the useFormState hook:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F17usvlseiunxws91szhg.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F17usvlseiunxws91szhg.jpeg" alt="after useFormState" width="800" height="697"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the code above, states have been removed because the parameter that the form action handler returns already contains the data for name and email, and the useFormStatus hook is used for the message.&lt;/p&gt;

&lt;p&gt;This hook returns an array similar to useState. The first value of the array is the value returned by its action, and the second value is the action function itself, which we place in the action attribute of our form. The values that the hook takes are firstly a function that we want to call during our form action, which returns something that goes into the same message, and the second value it takes is the initial value that we want the message to have.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useFormStatus():&lt;/strong&gt;&lt;br&gt;
Imagine we want to add error handling and loading states to our form in the above example. Let’s first look at how we would write the code using the previous approach:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ffzvj7n9dbgtaq4s89czg.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ffzvj7n9dbgtaq4s89czg.jpeg" alt="before useFormStatus" width="800" height="796"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s see how we can use the action and these two new hooks to handle the form with error and loading states:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fc9r18nze1esxok3z44dk.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fc9r18nze1esxok3z44dk.jpeg" alt="after useFormStatus" width="800" height="761"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the code, we see that the submit button has been moved into a separate component, where we use the useFormStatus hook. This hook returns an object that includes properties like data and pending, along with some other properties that aren't very useful.&lt;/p&gt;

&lt;p&gt;The data property is the data that has been obtained and submitted from the form, and the pending property is a boolean that remains true as long as our form action hasn't returned a result and is pending. Once the promise of our action is either fulfilled or rejected, the pending property becomes false.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: One of the pitfalls of this hook is that you cannot use it within the same component where the form exists; this hook only gives you the status of the form from the parent component.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fpll5nbccmccnuq0eie35.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fpll5nbccmccnuq0eie35.png" alt="useFormStatus pitfall" width="800" height="822"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What other new hooks do we have?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  use()
&lt;/h3&gt;

&lt;p&gt;This new hook that has been introduced to React is multi-purpose and is designed to simplify the process of fetching data from external sources as well as handling context:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Fetching Data from External Sources&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The way we used to fetch data:&lt;br&gt;
&lt;a href="https://media2.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%2F7mtd3vzlsrrv7t0vwddc.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F7mtd3vzlsrrv7t0vwddc.jpeg" alt="before use" width="714" height="773"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Previously, we needed a state and also a useEffect to fetch the data and set it in the state.&lt;/p&gt;

&lt;p&gt;Now, with the use hook, there’s no need for a state and useEffect:&lt;br&gt;
&lt;a href="https://media2.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%2Frfe3vogxt86njhmdtocz.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Frfe3vogxt86njhmdtocz.jpeg" alt="after use" width="714" height="677"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, something even cooler that we can do to enhance the user experience is to add a loading state while the data is being fetched. Surely you know that in the previous routine, we had to add a loading state, but Now, using React’s Suspense, the process has been made easier for us:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F9rhvixewvfpcdzw69bd6.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F9rhvixewvfpcdzw69bd6.jpeg" alt="suspense" width="734" height="749"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By wrapping our component with the Suspense component and adding a loading indicator as a fallback, the component will display the loading indicator until the data is fetched. This showcases the improved asset loading in the new version of React and signifies the end of React.lazy. This is not only due to this case but also because of the addition of server components and server-side pre-rendering, etc., which somewhat eliminates the need for React.lazy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. The second use of the use hook is for retrieving data from context&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Previously, we used the useContext hook in components to read the data available in our context:&lt;br&gt;
&lt;a href="https://media2.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%2Fa6wovdg4fo2ie3vojsli.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fa6wovdg4fo2ie3vojsli.jpeg" alt="useContext" width="560" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can use the use hook:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F5nz9gq5hvo7tw0mwgm6s.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F5nz9gq5hvo7tw0mwgm6s.jpeg" alt="use for context" width="560" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This hasn't made a significant difference, but overall, if you're using use within a component, you can also use it to read from the context, so there's no need to import another hook.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: In the new version of React, instead of  , you can simply use  , and there's no need to include the word 'Provider'.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  UseOptimistic()
&lt;/h2&gt;

&lt;p&gt;This hook is useful in scenarios where you need to interact with the server, such as in real-time applications. For instance, imagine when you like a post, you’re essentially sending data to the server to register that like, or when you send a message to someone, you’re sending data to the server to record the message and display it in the chat box. Now, consider that it might take a few seconds for the like or message to reach the server and be successful. During this time, the user would see that nothing happens when they like or send a message.&lt;br&gt;
the post isn’t liked, nor is the message sent...&lt;/p&gt;

&lt;p&gt;This is where we use the useOptimistic hook to perform an optimistic update. By clicking, we assume that the data has been successfully recorded on the server, so we preemptively insert fake data as if it has come from the server and was successful, and the user immediately sees that the post has been liked. When the real data comes from the server, it replaces our fake data, and the user doesn’t notice because as soon as they like it, they see the post has been liked, and with the arrival of the real data, the data doesn’t change. Or, for example, when a message is sent, we consider that message as registered and immediately show it in the chat box so the user thinks their message has been recorded. This method is called an optimistic update, as evident from the name of the hook.&lt;/p&gt;

&lt;p&gt;This improves the user experience by making the application feel more responsive and interactive. Here’s an example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F6rrhefj69gl1no95rs19.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F6rrhefj69gl1no95rs19.jpeg" alt="useOptimistic" width="800" height="846"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above, we see that we have a messages state which holds the real messages, and we have the useOptimistic hook that takes two parameters. The first is the initial value, which is equal to the real messages, and it takes a callback that optimistically returns the previous messages plus our own fake message. This hook returns an array containing two values: the first is the data that is returned from the callback, and the second is the callback itself, which we can invoke wherever we want to optimistically update the data.&lt;/p&gt;

&lt;p&gt;In the JSX, instead of mapping over the original messages, we map over the optimisticMessages because this includes the previous messages as well as our fake message, while the messages state remains untouched. Now, we have a form that contains the message input, and when the user writes their message and submits it, inside the sendMessage function, we see that it first calls our optimistic function and passes the message to it to update the optimisicMessages and consequently quickly update the UI. Then, it sends the message to the server to update the original data, and when the data returns, it updates the messages which contain the original data, causing the optimisticMessages to be refreshed with the real data, and the fake one is replaced with the real message.&lt;/p&gt;

&lt;p&gt;These were all the significant changes we witnessed in React 19.&lt;/p&gt;

&lt;p&gt;I hope you find them useful and enjoyable.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>programming</category>
      <category>frontend</category>
    </item>
    <item>
      <title>StyleX vs Tailwind?!</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Mon, 18 Dec 2023 13:23:33 +0000</pubDate>
      <link>https://dev.to/samaghapour/stylex-vs-tailwind-9cf</link>
      <guid>https://dev.to/samaghapour/stylex-vs-tailwind-9cf</guid>
      <description>&lt;p&gt;Today I'm going to talk about Stylex and the difference between this library and freamworks like Tailwind.&lt;/p&gt;

&lt;p&gt;What styleX offer and why or when should we use it over tailwind and other styling solutions?&lt;/p&gt;

&lt;p&gt;To answer this, let's take a brief look at styling solutions in web development history:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Pure CSS:
&lt;/h2&gt;

&lt;p&gt;CSS was developed to style documents, allowing developers to describe layouts in web pages. However, CSS had some issues:&lt;/p&gt;

&lt;p&gt;1.1 Global Scope: All CSS rules are equally accessible by all of the code, which can lead to conflicts between different CSS rules.&lt;/p&gt;

&lt;p&gt;1.2 Lack of Dynamic Capabilities: CSS is a static language and doesn't provide the functionality to create dynamic styles based on conditions.&lt;/p&gt;

&lt;p&gt;1.3 Difficulty in Managing Large Applications: As applications grow, managing CSS can become complex due to the global scope and the cascading nature of CSS.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. CSS-in-JS:
&lt;/h2&gt;

&lt;p&gt;To address these issues, the concept of CSS in JS emerged. It allows developers to write CSS directly within JavaScript, providing scoped and dynamic styles. However, CSS in JS also had its challenges:&lt;/p&gt;

&lt;p&gt;2.1 Performance Issues: CSS in JS libraries often inject styles into the DOM at runtime, which can lead to performance issues.&lt;/p&gt;

&lt;p&gt;2.2 Increased JavaScript Bundle Size: As styles are tied with JavaScript, it increases the size of the JavaScript bundle.&lt;/p&gt;

&lt;p&gt;2.3 Lack of Separation of Concerns: Mixing styles with JavaScript can lead to less maintainable code as it goes against the principle of separation of concerns.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Utility-first CSS:
&lt;/h2&gt;

&lt;p&gt;Frameworks like tailwind showed up that provide low-level classes for styling elements and have some advantages over CSS-in-JS libraries:&lt;/p&gt;

&lt;p&gt;Tailwind is faster to write and easier to read than CSS-in-JS, as it uses predefined classes instead of custom styles.&lt;/p&gt;

&lt;p&gt;Tailwind is more consistent and scalable, as it follows a design system and avoids style conflicts or specificity issues.&lt;/p&gt;

&lt;p&gt;Tailwind is more performant and lightweight, as it generates optimized CSS code and removes unused classes with PurgeCSS.&lt;/p&gt;

&lt;h2&gt;
  
  
  4.StyleX:
&lt;/h2&gt;

&lt;p&gt;And now Meta has come up with Stylex.&lt;br&gt;
the main comparison I saw so far is between styleX and tailwind and why or when we should use styleX over tailwind.&lt;/p&gt;

&lt;p&gt;StyleX addresses some of the problems and limitations of using Tailwind CSS in large-scale web applications.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;StyleX supports deterministic resolution, which ensures consistent styling outcomes regardless of the order of loading or applying the styles. This avoids selector precedence problems and unexpected styling changes that can happen with Tailwind.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;StyleX allows you to create custom styles co-located with the components, deterministic, and scalable. This gives you more flexibility than Tailwind, which relies on predefined utility classes that may not suit your needs or preferences.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;StyleX supports design tokens and utility classes, which make it easier to maintain a consistent design system across a large web application. You can define and use variables for colors, fonts, spacing, etc., and reuse them in your styles. You can also create and use utility classes for common patterns or modifiers, such as flex, hover, focus, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;StyleX is performant and lightweight, as it generates optimized CSS code and removes unused classes with PurgeCSS. It also uses a build-time system that avoids the runtime overhead of CSS-in-JS solutions.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It combines the best of all previous concepts: the simplicity and consistency of Tailwind CSS and the flexibility and expressiveness of CSS-in-JS.&lt;/p&gt;

&lt;p&gt;In my opinion, Tailwind has more value in small teams working rapidly without a set design system on small projects while StyleX is designed to support much larger projects, teams, and even groups of teams as we know the entirety of Facebook has been written in styleX and it was successful in decreasing the CSS size of the application.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>frontend</category>
      <category>javascript</category>
      <category>react</category>
    </item>
    <item>
      <title>Simplifying Data Management in React with React Query</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sat, 22 Apr 2023 16:33:12 +0000</pubDate>
      <link>https://dev.to/samaghapour/simplifying-data-management-in-react-with-react-query-29ef</link>
      <guid>https://dev.to/samaghapour/simplifying-data-management-in-react-with-react-query-29ef</guid>
      <description>&lt;p&gt;React Query is a popular JavaScript library that is widely used in React applications. The library provides us with powerful tools for fetching, caching, and updating data from APIs, helping us to manage our requests efficiently and build fast, smooth, and clean applications.&lt;/p&gt;

&lt;p&gt;The key benefits of this library that tempt every programmer to work with it are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Simplifying data management: React Query makes managing remote data in our application easier by providing powerful tools for fetching, caching, and updating data. It makes managing complex data scenarios such as pagination, optimistic updates, and server-side rendering easier.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Improving application performance: React Query has a smart caching and refetching mechanism that reduces unnecessary requests, resulting in significant improvements in application performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Eliminating unnecessary code: React Query frees us from writing unnecessary code for managing data, saving us time and allowing us to focus on the logic of our project and components without worrying about data fetching and caching.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Real-time updates: React Query allows us to have real-time data updates using websockets and other stream APIs, eliminating the need for users to manually refresh the page to update the data.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this article, we'll go over the key features of React Query and show you how to use it. We'll also discuss server states and client states and answer the question of whether React Query can be a useful tool for global state management.&lt;/p&gt;

&lt;p&gt;Installation:&lt;br&gt;
&lt;code&gt;npm install react-query&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After installing the package, we need to import QueryClientProvider and QueryClient in the index file as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fn8oceykqgfpnocisqri6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fn8oceykqgfpnocisqri6.png" alt="." width="800" height="448"&gt;&lt;/a&gt;&lt;br&gt;
We create a queryClient and pass it as a prop to QueryClientProvider, which is then wrapped around the App component. We can now easily use React Query in our components.&lt;/p&gt;

&lt;h2&gt;
  
  
  useQuery
&lt;/h2&gt;

&lt;p&gt;This hook is one of the most important hooks that React Query provides, and you'll use it a lot. This hook is used to fetch data from the server and cache it for subsequent calls:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fhwe62owaxs421ap7vtiu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fhwe62owaxs421ap7vtiu.png" alt="UseQuery" width="800" height="682"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see in the example above, this hook returns an object that we destructure to get the values we need.&lt;/p&gt;

&lt;p&gt;The first parameter we need to pass to this hook is the query key, which we use for naming. This means that we tell it to go to this endpoint, make this request, and cache the data with this name (in the example, with the name "todos") so that if we want to update the data later and it asks for the name, we can refer to it with the same name and update it.&lt;/p&gt;

&lt;p&gt;The second parameter we need to pass is an async function where we make the request and return the data.&lt;/p&gt;

&lt;p&gt;The properties that this hook returns are the most important ones, which you can see in the image above.&lt;/p&gt;

&lt;p&gt;The data property contains the data that was successfully returned from our request. The isLoading property is a boolean value that will be true if our request has not yet returned the data and is still in a pending state, and false otherwise. The isError property is the same, and will only be true if our request returns an error. We also have an Error property that we can use to display the error message, which is not in the example above.&lt;/p&gt;

&lt;p&gt;The cool thing about this is that once the data is successfully fetched and we have it, it will be cached for subsequent calls, and when the user wants to see the data again, they can see it instantly without any loading or delay, while React Query is running a new request in the background to see if the data has changed. If the data has changed, React Query will replace it with the cached data, and if not, the data will remain the same.&lt;/p&gt;

&lt;p&gt;As you can see, you're easily managing our request and all possible scenarios, such as when the request returns an error, is successful, or is loading. This is one of the key features of this library, and it allows us to avoid writing additional state management code for loading, error handling, try-catch blocks, and so on, making our code more efficient and clean.&lt;/p&gt;

&lt;h2&gt;
  
  
  useMutation
&lt;/h2&gt;

&lt;p&gt;We use this hook when we want to change the data, such as when we want to add an item to the data, remove an item from the data, or update the current data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fmn2vqn9h3l6npgu917zq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fmn2vqn9h3l6npgu917zq.png" alt="useMutation" width="800" height="1205"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see in the example above, this hook returns an object that we can destructure to access its properties and use them accordingly.&lt;/p&gt;

&lt;p&gt;The first parameter that we pass to this hook is an async function, where we make our request and return the data. If this function requires any parameters (like newTodo in the example above), we pass them to the mutate function when we call it.&lt;/p&gt;

&lt;p&gt;The second parameter is an object that we can use to perform various actions based on its properties. In the example above, we used the onSuccess property to specify a method that is called when the request is successful. In this method, we can refetch or invalidate the updated data. This tells React Query that our cached data is outdated and needs to be updated with the new data. This is where the query key comes in handy, as we can specify which data needs to be updated using this key in the invalidateQueries method.&lt;/p&gt;

&lt;p&gt;Regarding the queryClient, which we used its invalidateQueries method, I'll explain more about it later.&lt;/p&gt;

&lt;p&gt;Now, the properties that this hook returns include the mutate function, which we can use to update the data and execute the entire process that I just explained. The next property is isLoading, which is true until the mutation is completed (i.e., the update is successful, and the request is no longer pending). We can use this property to show a loading indicator while the request is in progress.&lt;/p&gt;

&lt;h3&gt;
  
  
  Optimistic Updates
&lt;/h3&gt;

&lt;p&gt;In addition to onSuccess, the second parameter of the useMutation hook also has other methods, such as onSettled and optimisticUpdate.&lt;/p&gt;

&lt;p&gt;Let's say you want to add an item to your data (send it to the server). You're sure that the data will be sent successfully, and you don't want to wait for a response from the server or see any loading indicator when adding the item. So, as soon as you click the add button, you manually add the item to your cached data. This allows the user to instantly see the new data without any delay or loading indicator.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fs67a7xab601544j3yny0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fs67a7xab601544j3yny0.png" alt="Optimistic Updates" width="728" height="1340"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The optimisticUpdate method is executed as soon as the request is made and does not wait for the final response of the request. In the example above, as soon as we made the request, we used the setQueryData method to tell React Query to update the cached data with the name "todos". We passed this name as the first parameter and a callback function as the second parameter. The callback function takes the current cached data as an argument and returns a new data array that includes the current cached data plus the newly added item. It's worth noting that we give the IDs manually and temporarily in this process, but when the request is complete, the cached data changes again, and the data we added in this method is deleted to add the updated data with the actual IDs.&lt;/p&gt;

&lt;p&gt;Now, the problem is that if for any reason the server returns an error and we cannot update the cached data, the fake data we added in optimisticUpdate will remain in the cache, even though we don't really have such data and just wanted to show it temporarily until the real data arrives.&lt;/p&gt;

&lt;p&gt;This is where the next key method comes in, which I mentioned, onSettled. This method is called after the server returns a response, regardless of whether it was successful or returned an error. We can use it to tell React Query to remove the fake data we added in optimisticUpdate if the server returned an error, so that only the original data remains.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F4agc95cya20uqu3h1viu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F4agc95cya20uqu3h1viu.png" alt="onSettled" width="540" height="1264"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The onSettled method has several arguments, but we only need error and context. We use the error argument to check if it's true and if an error was returned, so that we can delete the fake data. Then, we use the setQueries method again to retrieve the cached data and filter it to keep only the items whose ID is not the same as the ID of our fake item, so that we keep only the original cached data. We return the cached data to its previous state in this way.&lt;/p&gt;

&lt;p&gt;In addition, in our request, we check if response.ok is false and throw an error, so that onSettled is called when an error occurs. Also, we return the ID of our fake item in optimisticUpdate and use it as the context argument in onSettled to filter the data.&lt;/p&gt;

&lt;p&gt;Overall, this process is called optimistic update and is one of the key features of this library.&lt;/p&gt;

&lt;h2&gt;
  
  
  useQueryClient
&lt;/h2&gt;

&lt;p&gt;We used this hook in the above examples that is used to access the query client, which is responsible for managing the cache, changing cached data, and invalidating them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fbrp1eatlgixbmpjy7ghc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fbrp1eatlgixbmpjy7ghc.png" alt="useQueryClient" width="800" height="752"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The most important methods that this hook provides are:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;setQueryData&lt;/strong&gt;: This method updates the cached data for the query key that we provide to it.&lt;br&gt;
&lt;strong&gt;getQueryData&lt;/strong&gt;: This method returns the cached data for the query key that we provide to it.&lt;br&gt;
&lt;strong&gt;invalidateQueries&lt;/strong&gt;: This method updates the cached data for the query key that we provide to it by refetching or requesting the data from the server again.&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching options
&lt;/h2&gt;

&lt;p&gt;When we used useQuery in our first example to fetch data, we only talked about its first two parameters, which include the query key and our request. Now we have a third parameter that we can use to configure and manage its caching and request capabilities. The most important properties for configuring these options are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;staleTime: We use this property to determine how long the cached data should remain stale before being refetched. This property takes a numeric value in milliseconds.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;cacheTime: We use this property to determine how long the data can remain in the cache before being automatically purged, which helps us manage our cache size. This property takes a numeric value in milliseconds.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;refetchOnMount: We use this property to determine whether the query should refetch its data when the component mounts. This property takes a boolean value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;refetchOnWindowFocus: We use this property to determine whether the query should refetch its data when the window regains focus, which helps us keep the data up-to-date when the user switches between pages in our application. This property takes a boolean value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;refetchInterval: We use this property to determine how often the query should automatically refetch its data. This property takes a numeric value in milliseconds.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;retry: We use this property to determine how many times the query should retry its request when it encounters an error from the server. This property helps us better manage server errors and keep our application responsive. This property takes a numeric value for the number of retries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;retryDelay: We use this property in conjunction with the retry property to determine how often the query should retry its request. This property helps us avoid overwhelming the server with too many consecutive requests. This property takes a numeric value in milliseconds.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;staleWhileRevalidate: We use this property to show the cached data to the user while the query fetches new data from the server in the background and updates the cached data. This property takes a boolean value.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By using these configuration properties, we can have different strategies for caching in our application. Here are two strategies that I will explain below, and you can either use them or create your own strategy based on the needs of your project:&lt;/p&gt;

&lt;h3&gt;
  
  
  stale-while-revalidate strategy:
&lt;/h3&gt;

&lt;p&gt;This strategy involves showing the user the cached (stale) data while fetching new data in the background and updating the cached data with it. This strategy helps us reduce the number of times the user has to wait for data and see a loading spinner, and allows them to instantly view the available data when they need it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fo9iiwr0eia7ywy63hfiq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fo9iiwr0eia7ywy63hfiq.png" alt="stale-while-revalidate strategy" width="800" height="878"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  network-first strategy:
&lt;/h3&gt;

&lt;p&gt;With this strategy, we prioritize fetching fresh data from the network over cached data, and it is suitable when we want to ensure that the data the user is seeing is always up-to-date, even if it comes at the cost of sacrificing some performance:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fv2q6htjqg3o8r4xmpvx3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fv2q6htjqg3o8r4xmpvx3.png" alt="network-first strategy" width="800" height="905"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, by setting cacheTime and staleTime to one minute, we are telling the system to purge the cache and refetch new data every minute. By setting refetchOnMount to false, we are instructing the system not to refetch data on mount and only do so every minute. With retry set to 3, we are telling the system to retry fetching data up to three times if an error occurs.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: If one minute passes and the system fails to fetch new data after three retries, it will check the cache and display any available data. If there is no data available, it will display an error.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Can we use React Query as a global state management tool and get rid of redux and other state management tools?
&lt;/h4&gt;

&lt;p&gt;To answer this question, lets first understand types of states:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Client State and Server State&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Client states are the states that are managed on the client side (e.g., user's browser) and their changes depend on the user's action within the application. These changes do not require sending a request and can be managed locally. Examples of client states include the user's login status, the theme they have selected for the site, the language they have selected for the site, and the data entered into form inputs that have not yet been submitted.&lt;/p&gt;

&lt;p&gt;Server states, on the other hand, are the states that are managed on the server side (backend) and their changes require sending a network request. Examples of server states include the list of products available for purchase in an online store, the list of articles published on dev.to, etc...&lt;/p&gt;

&lt;p&gt;So, to answer your original question, the React Query library is specifically designed and created for &lt;strong&gt;managing requests and caching data&lt;/strong&gt;. Although it is possible to use it for global state management, it is not recommended for client states as it may add unnecessary complexity. &lt;strong&gt;&lt;a href="https://dev.to/samaghapour/redux-toolkit-easier-than-redux-4bje"&gt;Redux Toolkit&lt;/a&gt;&lt;/strong&gt; is a better option for client state management, as it provides similar features to React Query for managing requests and caching data, as well as handling all types of states.&lt;/p&gt;

&lt;p&gt;However, depending on your project requirements, you can choose to use either library, or even both. Ultimately, it's up to you to decide which package suits your needs best. I just wanted to introduce you to this great library that has a lot of features to offer. Hopefully, it was helpful for you.&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Redux toolkit, easier than Redux!</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Wed, 03 Aug 2022 15:32:00 +0000</pubDate>
      <link>https://dev.to/samaghapour/redux-toolkit-easier-than-redux-4bje</link>
      <guid>https://dev.to/samaghapour/redux-toolkit-easier-than-redux-4bje</guid>
      <description>&lt;p&gt;We have already explored Redux in the &lt;a href="https://dev.to/samaghapour/redux-is-easier-than-you-think-1i0p"&gt;"Redux is easier than you think!"&lt;/a&gt; article and we learned have to use it, still there are some problems when it comes to using redux. those problems are: 1. redux configuration is too complicated 2. redux requires too much boilerplate code 3. it doesn't do anything helpful by itself and we have to install packages like redux-thunk, redux-saga,redux-persist, etc...&lt;/p&gt;

&lt;p&gt;Now redux toolkit is here to solve most of our problems by giving us all we need from redux to manage our states and data.&lt;br&gt;
redux-toolkit is a suger around redux that does the same thing redux does under the hood, but we don't need to go through all of those complicated configurations.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: if it is the first time that you want to learn redux and you choose redux-toolkit, I encourage you to check out the &lt;a href="https://dev.to/samaghapour/redux-is-easier-than-you-think-1i0p"&gt;redux article &lt;/a&gt;first, so you would have some idea about what redux is and what it solves because we are not going to talk about those things here.&lt;/p&gt;

&lt;p&gt;I wrote this article supposing you know nothing about redux but meanwhile, I put some "redux notes" for the people who are familiar with redux or have read the redux article before. So if you are not one of those who already knows about redux, you'd better not to read "redux notes" if you don't want to get confused.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Install packages that you need
&lt;/h2&gt;

&lt;p&gt;npm install @reduxjs/toolkit react-redux&lt;/p&gt;

&lt;p&gt;@reduxjs/toolkit is the all-in-one package that includes everything we need and we don't have to install redux-thunk or any other redux packages except react-redux. we use redux to create store and react-redux is just the way for react to communicate with redux, e.g: updating global state, reading global state,...&lt;/p&gt;

&lt;h2&gt;
  
  
  2.create **features **folder in src folder of your project
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Faa36cbbu35wusgx7vwyh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Faa36cbbu35wusgx7vwyh.png" width="366" height="268"&gt;&lt;/a&gt;&lt;br&gt;
After creating the features folder, we create a folder for each one of our actions, in the above image which is the content of the features folder, we created a folder named allProduct that is related to products actions and a folder named cart which is related to actions like adding or removing the product from the cart or even getting added items in the cart...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F1evqp2u2xgu4gjnsswef.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F1evqp2u2xgu4gjnsswef.png" alt="cart folder's content" width="224" height="139"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each folder contains two files: 1. action.js 2. xxxSlice.js ( you can put anything instead of xxx, but in our example it is cartSlice because it is in the cart folder).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;gt; Redux note: imagine slice file as a reducer, just like reducer file that we used to name it xxxReducer, we name slice file like xxxSlice and we are not going to create reducer files anymore.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;action.js contains all the actions that we need like adding product to cart, removing product from cart , etc... :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F32gwsn9vbem9jtgcyho6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F32gwsn9vbem9jtgcyho6.png" width="653" height="755"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;CreateAsyncThunk is a function from redux-toolkit that accepts a Redux action type string and a callback function to fetch the required data and return it. if our requests need anything like id or data,... we just pass them as parameters of our async callback function. as you can see in the above image when we need one parameter we can just pass it to our callback easily (like deleteFromCart action), but if we need more than one parameter, then we have to pass them as an object(like updateCart,addToCart actions) because the second argument of our async callback is not for parameters.&lt;/p&gt;

&lt;p&gt;after fetching the data with Axios or fetch or anything else) we return the data and this async callback is going to dispatch an object with the property named payload and the value of this payload is the data that we received from the server.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;gt; Redux note: you might have noticed with the createAsyncThunk method we don't need to dispatch an object with type and payload anymore and by passing a unique string as the first argument of this function we are actually sending the type and the async callback is going to handle payload itself.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now, we need a slice to take care of these actions and after dispatching one of these actions, the slice is going to receive the type and payload and send the payload to the global state of our application.&lt;/p&gt;

&lt;p&gt;So, we create cartSlice for above actions:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fopuhz2yr86agi0ditpf8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fopuhz2yr86agi0ditpf8.png" alt="src/features/cart/cartSlice.js" width="671" height="704"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;createSlice comes from redux-toolkit and it is a function that accepts an object of options:&lt;br&gt;
name option for naming the slice,&lt;br&gt;
initialSatate option for defining the initial state,&lt;br&gt;
extraReducer option for defining different cases for our actions and state updates, extraReducer is a function that receives a builder and inside this function, we need to define our cases like above, addCase method of builder accepts two parameters: 1. the action(imported from action.js) with the status of the action like fulfilled, rejected and pending, 2. the callback that updates the state and this callback accepts two parameters first the initial state that we already declared and the action which has a payload property that is equal to what the action returns.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: you might have noticed the name that we gave to createSlice is the name that we put in the first part of the type string in the first parameter of createAsyncThunk, this way, we are actually saying that the slice with the name of 'cart' will look over this action that has the type of 'cart/addToCart' or 'cart/deleteFromCart',...&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;&amp;gt; Redux note: just like reducer that we had an initialState in it, in the createSlice we have the same thing.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the above example if the getCart action has been dispatched and received the data successfully, the first case that we add inside extraReducers is going to get invoked and update the value property of our state with the data that comes from the action.&lt;/p&gt;

&lt;p&gt;This is another slice example with more cases:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F4n1tc9adq3xy37pfj73p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F4n1tc9adq3xy37pfj73p.png" alt="src/features/productDetails/productDetailsSlice.js" width="643" height="757"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, we have rejected and pending status too, so we can add a case for those statuses and tell redux whenever the action was dispatched and it was still in pending status or rejected status, invoke this case and update the error or loading property of our state so we can use it in our page to show a loading spinner or an error alert,... &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: in redux, we usually declare a specific state for loading and set its value to true before making a request and set it to false after the request. but with redux-toolkit, we don't need to do that anymore.&lt;/p&gt;

&lt;p&gt;Important note: objects are immutable in javascript so we are not allowed to change them and we had to create a new object and copy the old object properties into it and Re-initialization the property we want to update. like this:&lt;br&gt;
{...initialState,value: payload.action}&lt;br&gt;
This way could be a little bit annoying for some people, so we don't have to do it this way with redux-toolkit and as you can see in the above examples inside cases, we are actually changing the property of our state object so easily.&lt;br&gt;
redux uses immer.js under the hood to turn our cases just like the way before(creates a new object and copies the old one into it and updates the property that we want) so we don't have to deal with that annoying syntax anymore.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We have another option for createSlice which is reducers: this option is used for synchronous actions and we don't even need to define actions in a separate file,  reducers is an object of our sync actions these actions accept two parameters, first the initial state and the second is an action  that is the first parameter that we gave to our action when we dispatch it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fe6p474z2f1y3vpph5qw4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fe6p474z2f1y3vpph5qw4.png" alt="reducers option" width="800" height="803"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After declaring an action inside reducers, createSlice gives us the object of an actions that contains all the actions we defined inside the reducers option and just like the example above, we can destructure it and export it.&lt;/p&gt;

&lt;p&gt;You also might have noticed in all slice examples we have the last line that exports xxxSlice.reducer. createSlice gives us a reducer to use in our global store to be able to access the states we declared in slice files anywhere we want.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Create &lt;strong&gt;store.js&lt;/strong&gt; in src folder
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8hlymzxeybg59s2lwe5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8hlymzxeybg59s2lwe5i.png" alt="src/store.js" width="800" height="393"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;configureStore accepts an object that has an option named reducer and the reducer option is an object that contains all the reducers that we have exported from our slices and whenever we dispatch an action the data is going to be saved here at the end.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;gt; Redux note: by using configureStore we don't need to use combineReducers or even config reduxDevTool anymore, because configureStore does all of that for us.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Add store to provider in src/index.js
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fsewk2ya7rvp0qpilb1xc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fsewk2ya7rvp0qpilb1xc.png" alt="src/index.js" width="800" height="505"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The provider comes from react-redux and we use it by wrapping it around the App component and we pass the store that we created with configureStore to the provider to make our states available inside all the components&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Using actions and reducers
&lt;/h2&gt;

&lt;p&gt;Well, if I want to be brief, we either want to dispatch an action to update the data or read the updated data from the global state.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Dispatch an action to update a data:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fqhhid58h3sl37qjugz0n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fqhhid58h3sl37qjugz0n.png" alt="dispatch the action" width="800" height="919"&gt;&lt;/a&gt;&lt;br&gt;
In above example, we are dispatching the addToCart action and because it needs two parameters, we have to put them inside an object. we dispatch the data by using the useDispatch hook that comes from react-redux.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Read the updated data inside global state:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fesuah0eamvyq9fbp4d79.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fesuah0eamvyq9fbp4d79.png" alt="read the data inside global state" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example, we are using useSelector hook that comes from react-redux and accepts a callback that has one parameter which is our global state (reducer option inside the condifgureStore object). whenever we dispatch an action like addToCart or getCart or deleteFromCart the cartSlice is going to watch out and if the case that we add inside extraReducer was available so it is going to update the initial state and pass it to the cart property inside the reducer option of the configureStore method.&lt;/p&gt;

&lt;h2&gt;
  
  
  RTK Query
&lt;/h2&gt;

&lt;p&gt;If you are looking for a different redux-toolkit structure that helps you with data fetching and data caching,... you can forget about all the structure above and use redux-toolkit in the way that I am going to tell you now: &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Create &lt;strong&gt;services&lt;/strong&gt; folder inside src folder of your project
&lt;/h2&gt;

&lt;p&gt;This folder contains one file which is xxxApi (you can put anything instead of xxx, in our case we are going to call it onlineShopApi.js)&lt;br&gt;
This file looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fvzezajek12sn9x6m0rkq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fvzezajek12sn9x6m0rkq.png" alt="src/features/onlineShopApi.js" width="800" height="756"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;createApi is a function that accepts an object of options:&lt;br&gt;
reducerPath: The reducerPath is a unique key that your service will be mounted to in your store.&lt;/p&gt;

&lt;p&gt;baseQuery:  it can be equal to the fetchBaseQUery which is a very small wrapper around fetch that aims to simplify requests. it accepts an object and we can put properties like baseUrl to simplify our requests.&lt;/p&gt;

&lt;p&gt;endpoints: it is equal to a function that receives the build parameter and returns an object of properties and each property is equal to builder.query or builder.mutation which is a function that receives an object:&lt;br&gt;
If the endpoint we have is for getting some data with the method of GET, we need to use builder.query which receives an object that contains a function named query and returns an string of our endpoit.&lt;br&gt;
If the endpoint we have is for updating some data with methods like POST, DELETE, PATCH, or PUT, we need to use builder.mutation which receives a function named query and returns an object with url(endpoint string), method(PUT,...), and body property (if we need it).&lt;/p&gt;

&lt;p&gt;Any data or id or whatever we need for our request, we can receive it as a parameter of query function and use it (like getProductDetails query or addToCart mutation in the above example), and don't forget if it is more than one parameter you need to pass it as an object(like addToCart mutation).&lt;/p&gt;

&lt;p&gt;Now, createApi gives us a hook for each query or mutation we declared inside endpoints and we can destructure these hooks and export them to use them in our components (just like the last line in the above example).&lt;br&gt;
these hooks are named by createApi with this format:&lt;br&gt;
for builder.query endpoints:&lt;br&gt;
use + your given name + Query &lt;br&gt;
like : useGetCartQuery , useGetProductDetailsQuery hooks in above example.&lt;/p&gt;

&lt;p&gt;for builder.mutation endpoints:&lt;br&gt;
use + your given name + Mutation&lt;br&gt;
like : useDeleteFromCartMutation, useAddToCartMutation hooks in above example.&lt;/p&gt;

&lt;p&gt;createApi also gives us a reducer to use inside the reducer option of configureStore object that we are going to use in the next step.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Create store file in src folder of your project
&lt;/h2&gt;

&lt;p&gt;The configureStore options is a little bit different from what you saw in previous structure:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F10mvmshlovtkkk9d2if8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F10mvmshlovtkkk9d2if8.png" alt="src/store.js" width="800" height="307"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We use the reducerPath option of our api to name the reducer it returns inside global state.&lt;/p&gt;

&lt;p&gt;configureStore sets some middlewares to our store by default(like thunk middleware to make redux able to use async actions)  but when we use the rtk query structure we want to also add the middlewares our api returns to our store. So, just like in the above image, we declare a middleware option that is equal to a function that accepts a function named getDefaultMiddleware and we call this function to get an array of all the default middlewares and also concat the middleware that comes from our api to this array.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;gt; Redux node: each middleware that we put inside middleware array in configreStore is going to be used with applyMiddleware that we had inside redux.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: the middlewares that come from our api are going to help us in caching, invalidation,... processes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  3. Add store to provider in src/index.js
&lt;/h2&gt;

&lt;p&gt;This step is the same step that we had in the previous structure.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Using query and mutation hooks
&lt;/h2&gt;

&lt;p&gt;We either want to request data and get something by query hooks or update data by deleting, editing, or creating with mutation hooks.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using query hooks to get data:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fn8yqf1sl1jgw899ap3fx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fn8yqf1sl1jgw899ap3fx.png" alt="queries" width="800" height="630"&gt;&lt;/a&gt;&lt;br&gt;
As you see in the above example, query hooks give us an object of fetch results like data, loading, error, etc... &lt;br&gt;
and we don't have to deal with declaring loading or error in our states. as soon as the component mounts, the request is going to be made and next time the data that has been returned before, is going to be cached(it means we just have loading for the first time that the data is empty).&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using mutation hooks to update data:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F834w9ulgb7sigb7qw5sz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F834w9ulgb7sigb7qw5sz.png" alt="mutations" width="800" height="595"&gt;&lt;/a&gt;&lt;br&gt;
As you see in the above example, mutation hooks give us a tuple. The first item in the tuple is the "trigger" function and the second element contains a results object with data, isLoading, isError,... properties.&lt;/p&gt;

&lt;p&gt;This was the second way and structure to use redux-toolkit, the main thing that you should consider is that either in the first structure or in the second one, each method has lots of options and configurations that I am not able to talk about all of them in this article.&lt;/p&gt;

&lt;p&gt;I tried to give you all the important and main concepts that you should know about redux-toolkit and be able to start using it, but if you want to learn more about it you can check out redux toolkit documentation.&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>redux</category>
    </item>
    <item>
      <title>Performance optimization tips for React projects</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Thu, 07 Jul 2022 11:26:19 +0000</pubDate>
      <link>https://dev.to/samaghapour/performance-optimization-tips-for-react-projects-4mj</link>
      <guid>https://dev.to/samaghapour/performance-optimization-tips-for-react-projects-4mj</guid>
      <description>&lt;p&gt;In this article, we are going to talk about tips and techniques for making our react projects' performance faster and more user-friendly.&lt;/p&gt;

&lt;p&gt;by reading this article you meet the other react hooks and finish the hooks journey that we started &lt;a href="https://dev.to/samaghapour/react-hooks-26p0"&gt;before&lt;/a&gt;, and you also update your react knowledge by reading about new react 18 features, and at the end, you learn so many techniques for optimizing your react projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. useTransition()
&lt;/h2&gt;

&lt;p&gt;This one is one of the coolest hooks that was introduced in React 18 and it's really helpful!&lt;br&gt;
If I want to explain it, I would start with an example:&lt;/p&gt;

&lt;p&gt;Imagine you have thousands of products that you are showing on your page and you have a search input that filters those thousands of products by typing and it shows the related result by pressing any button on your keyboard, the whole filtering process is going to start again to show the updated result and now the problem is we have too many products that cause our filtering process to take much more time and that makes our input functionality slow or in other words, The longer the filtering process gets, the later your pressed letter is going to show up in the input and you may know this problem as being laggy.&lt;/p&gt;

&lt;p&gt;you can check out &lt;a href="https://codesandbox.io/s/billowing-waterfall-ky876p?file=/src/styles.css" rel="noopener noreferrer"&gt;this demo&lt;/a&gt; to see what I am talking about. just try to search 4444 to filter the products and then, remove the 4444 at ones from the input. you will notice that it takes a few amounts of time to remove 4444 from the input.&lt;/p&gt;

&lt;p&gt;This process in react is like this: we have a query state to set the value of search input onChnage and the value of state is passed to the input(state changes and input gets updated) and also we have a state that contains our products and inside search input onChnage handler beside setting query state we also filtering products and setting products state to the filtered products:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fss7dtzcpp800en4fjheb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fss7dtzcpp800en4fjheb.png" alt="filtering process" width="800" height="755"&gt;&lt;/a&gt;&lt;br&gt;
Now, what is the main reason for having laggy and not user-friendly search input?&lt;br&gt;
React tries to update all states and then just re-render the component and show the updated UI with all changes at once. it means even though query state updates much faster because it does not require any special process or anything like that but it has to wait until other states like products state that require expensive process and takes more time to get finished and then at the end, updated query state and updated products state get passed to the screen. by knowing this process, we can understand that all states are urgent in react and none of them has low priority and react re-renders the component one time with all new state changes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: in the past, most people used to fix this laggy problem by limiting the data length on the page and implementing features like pagination to make the filtering process much lighter and fast, But what about nowadays?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Concurrent rendering
&lt;/h3&gt;

&lt;p&gt;Now, React has a hook for this problem which is useTransition and beside pagination, this hook makes react to be able to have non-urgent states:&lt;br&gt;
We want any states like query state that does not require any process, to get updated and be shown up on the screen and don't have to wait for other states' updating process, and then, whenever these heavy states get updated, they can be shown up on the screen which means we want react to be able to re-render the component multiple times which is called "concurrent rendering".&lt;/p&gt;

&lt;p&gt;In the real-world example, it is like me having a plan to write this article, and meanwhile, I have to eat lunch. So do you think this makes sense that I finished my article, But I don't publish it just because I'm waiting for my lunch to get ready and then I eat my lunch, and just by eating the last piece of my lunch, I publish my article so this way I finished both of them at the same time!! Well, it does not make sense at all. with the concurrent option, I can write my article, and meanwhile, I put my lunch into the oven to get ready, and as soon as I finish my article I publish it and don't wait for lunch to get ready because it has low priority now! so whenever lunch gets ready I eat my lunch. this way everything is faster and better right?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: you need to use the new method of react-dom to make react able to use the concurrent rendering option:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F7eql0mw0nlqli2sk2fey.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F7eql0mw0nlqli2sk2fey.png" alt="react-dom" width="800" height="506"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So how should we use useTransition hook anyway?&lt;br&gt;
This hook returns an array with two items: 1. isPending, 2. startTransition&lt;/p&gt;

&lt;p&gt;The "isPending" item is boolean, and its value is true until our non-urgent state gets updated and we can use this item for showing loading stuff in UI to have a better user experience.&lt;/p&gt;

&lt;p&gt;The "startTransition" item is a function that accepts a callback and inside this callback, we set all the states which should have low priority to make react understand that it should not wait for these states to get updated and they are non-urgent states, and it can render component first when urgent states get updated and second when these non-urgent states get updated:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fyot3xgs8i0b0t4qdvkp8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fyot3xgs8i0b0t4qdvkp8.png" alt="useTransition" width="693" height="856"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;you can check out &lt;a href="https://codesandbox.io/s/mutable-cache-ihebzu?file=/src/styles.css" rel="noopener noreferrer"&gt;the demo&lt;/a&gt; to try this and see how better it is. there is no laggy input or things like that and also we have a loading for non-urgent state updating:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fiw3scfcrqdiiuru9zez1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fiw3scfcrqdiiuru9zez1.png" alt="loading for non-urgent state updating" width="795" height="508"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: remember to use this hook only in these situations, because react does some extra things to implement concurrent rendering and make those states non-urgent, So your state might not be worth the pressure of that extra work and make the performance even worse!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  2. useDeferredValue()
&lt;/h2&gt;

&lt;p&gt;This one does the same job as useTransition does, but the difference is that we use useTransition when we can use the setState function inside our component and there are times that we just get the state as a prop and we don't have access to the setState function inside our component so thas is the time that we use useDiferredValue hook to make that state non-urgent.&lt;br&gt;
This hook only accepts one parameter and that is the state:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fdkuu0mmp40cbli660iko.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fdkuu0mmp40cbli660iko.png" alt="useDiferredValue" width="650" height="779"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: remember that we don't have isPending option with this hook, so try to use useTransition hook as much as possible instead of useDeferredValue hook.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  3. useMemo()
&lt;/h2&gt;

&lt;p&gt;Imagine we have component like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fsd4fuu7e40kr8turgyzk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fsd4fuu7e40kr8turgyzk.png" alt=" " width="800" height="635"&gt;&lt;/a&gt;&lt;br&gt;
We have a function named greetingFunc and this function performs an expensive process and returns a string with the name argument and we have a greeting variable that is equal to the returned value of greetingFucn (basically, every time we define the greeting variable, we are calling the greetingFunc, and giving it a name state to go through the expensive process and return the value we want ) and we also have a theme variable that depends on the darkTheme state value and changes the UI style by changing the darkTheme state.&lt;/p&gt;

&lt;p&gt;Now, if we change the darkTheme state by clicking the change theme button, react is going to re-render the component and it means that the greeting variable is going to be declared again, and calls that greetingFunc and gives it the same name state which has not changed at all! ( in other words, by changing the darkTheme state we are also calling the function with an expensive process that has the same input and same output as before!). So we want to call that expensive function just when its input is different and avoid the unnecessary expensive process. we want to memorize the returned value of that function, so if next time it was going to get called again, it compares the input that it receives and if it is different from before, then it can be invoked again otherwise not.&lt;/p&gt;

&lt;p&gt;That is the job that useMemo handles. useMemo memoizes the returned value of our expensive function and if next time react wants to call this function again, it compares the old input and new input which you can assume input as a dependency and if the input value has not been changed, it means the returned value is the same, So useMemo hook memoized it already ;)&lt;/p&gt;

&lt;p&gt;useMemo hook accepts two parameters, first, a callback that returns the function we want to memorize, and second an array of dependencies to tell react whenever these dependencies values have been changed, react calls our function, and goes through the expensive process:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F23yaczfxbt149tdamyef.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F23yaczfxbt149tdamyef.png" alt="useMemo" width="800" height="655"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can check out the &lt;a href="https://codesandbox.io/s/sleepy-goldstine-7q5bin?file=/src/styles.css" rel="noopener noreferrer"&gt;demo&lt;/a&gt; and try this, ones by using the useMemo hook and ones without the useMemo to see whenever you change the darkTheme state, does greetingFunc is called again or not?&lt;/p&gt;

&lt;h2&gt;
  
  
  4. useCallback()
&lt;/h2&gt;

&lt;p&gt;There are two main reasons to use useMemo and useCallback hooks :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Referential equality &lt;/li&gt;
&lt;li&gt;Computationally expensive calculations&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We talked about the second one (how we avoid expensive calculation processes with useMemo hook). So useCallback hook's job is to handle the first one ( referential equality ).&lt;br&gt;
Let's start with an example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Favgkz32gm1ot58u7e9w4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Favgkz32gm1ot58u7e9w4.png" alt=" " width="800" height="600"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see in the above example, there are times that we pass a function as a prop to the childComponent which is DummyButton in our example, now if you change the state in the parent component with the increase button what would happen?&lt;br&gt;
The parent component is going to get re-rendered again, and that causes our onClick function (which we pass to childComponent as a prop) to get created again. so in javaScript when there are two functions or objects which look like each other they aren't actually equal! because they have a different reference in memory, and by that, it means the onClick function is different from before even though the output and everything are the same and whenever the childComponent props get changed, react is going to re-render the childComponent again, just because the reference of the new prop is different from the old one and that is the &lt;strong&gt;Referential equality&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That is the time for the useCallback hook to show up, just like useMemo, useCallback receives two parameters, first, the function we want to memorize, and second, the array of dependencies. the only syntax difference is in useCallback we don't return the function inside the callback parameter, we give the target function as the callback ( in useMemo we pass it a callback which returns the target function). So, by using the useCallback hook, whenever the parent component gets re-rendered, react is going to compare the old and new dependencies values in the useCallback second parameter and if they are different it is going to create the function again with a different reference that causes the childComponent to get re-rendered again and if the dependencies have not been changed so there is no reason to create that function with new reference and re-render the childComponent again.&lt;br&gt;
The above example can be fixed by using useCallback hook like the below image, and also you can try it online by clicking &lt;a href="https://codesandbox.io/s/elegant-dubinsky-zzde6m?file=/src/styles.css" rel="noopener noreferrer"&gt;this demo&lt;/a&gt; to add useCallback and see how it works:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F0amh20bdc1f8l1cthmet.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F0amh20bdc1f8l1cthmet.png" alt="useCallback" width="800" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: the difference between useMemo and useCallback is that useMemo memorizes the &lt;strong&gt;returned value of the function&lt;/strong&gt; to avoid &lt;strong&gt;invoking ** that again and fix the "Computationally expensive calculations" and useCallback memorizes the **function itself&lt;/strong&gt; to avoid &lt;strong&gt;creating&lt;/strong&gt; that function again and fix the "Referential equality".&lt;/p&gt;

&lt;p&gt;Note: use these two hooks just for these two reasons that we talked about above, otherwise if you wrap any cheap and little functions with these two hooks, react is going to compare dependencies every time and it's just not worth it for small things, and this causes performance issues&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  5. React.memo()
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fj4jc7lt8v2pqgpewcsem.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fj4jc7lt8v2pqgpewcsem.png" alt=" " width="800" height="502"&gt;&lt;/a&gt;&lt;br&gt;
When we have a bunch of child components inside the parent component, by re-rendering the parent component, all of its child components are going to get re-rendered again even if their props haven't been changed or even if they don't receive any props, it does not matter, react is going to re-render them anyway and this makes performance sad!&lt;br&gt;
react must compare the props of the component before re-render to avoid unnecessary re-rendering and if the new and old props are different so then react can re-render the component, otherwise not, and we can do this by using memo.&lt;br&gt;
react.memo receives a callback which is the whole component that we want to memorize. when we wrap our component with react.memo, react is going to compare component's props every time and avoid unnecessary re-rendering.&lt;br&gt;
In the above image, we haven't used react.memo, so whenever the App component gets re-rendered by changing the state, react is going to re-render the ChildComponent again. To fix this problem with react.memo we do it this way:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fdo7icudmebdqd0abu32n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fdo7icudmebdqd0abu32n.png" alt="React.memo" width="800" height="508"&gt;&lt;/a&gt;&lt;br&gt;
you can try it out by clicking &lt;a href="https://codesandbox.io/s/falling-cherry-r2hkdq?file=/src/styles.css" rel="noopener noreferrer"&gt;this demo&lt;/a&gt; and use the above example ones with memo and ones without it, to see whenever you update the state by clicking the 'update parent component' button if ChildComponent gets re-rendered again and 'child component got re rendered again!' text logs again or not?&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Code-Splitting with lazy &amp;amp; Suspense
&lt;/h2&gt;

&lt;p&gt;When we want to use a bunch of components in our component we just import them in order to use them, and importing the components is completely static, and components get imported at compiling time and we can't tell react to load that imported component in parent component just whenever we need it or in another word, we can't make it dynamic import to avoid time-wasting on loading the components that user might even not scroll down to see those components.&lt;br&gt;
one of the most use-cases of this is when we are defining different routes in the App component and importing all page components to use them for each route, and we want to load each page component whenever the route is the one we gave it, and otherwise react is going to load all of them at ones without caring about paths. And that is time for code splitting by using lazy and suspense that makes us able to load components dynamically and whenever we need it.&lt;br&gt;
lazy and suspense help us to load component whenever we need that specific component, so this way we don't have to load all of them at once and it helps performance a lot:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fvadu1dadmemxkx59b4dx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fvadu1dadmemxkx59b4dx.png" alt="lazy and suspense" width="800" height="672"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we are importing Home and Panel components dynamically and whenever the route is ' / ' home component is going to be loaded and whenever the route is ' /panel ',  panel component is going to be loaded.&lt;br&gt;
lazy receives a callback that returns an import method and the import method receives the component path in the project (5th &amp;amp; 6th line in the above example).&lt;br&gt;
All the components that have been imported with lazy, should be wrapped with suspense and the suspense receives a prop named fallback and fallback value is a JSX and it is for loading purposes to show the user a loading until the requested component gets ready and loaded and that is really a good user experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. React Lazy Load Image Component
&lt;/h2&gt;

&lt;p&gt;Let's say we have a page and we get 200 images from the server to show on that page and whenever the user navigates to that page, it sends HTTP requests and loads all 200 images one by one and that is going to take time to load them all, while the user might not even want to scroll down to see at least 10 out of 200 !! so why should we load the images that don't show up on the screen yet?&lt;br&gt;
In this case, we use a library called " React Lazy Load Image Component " and its job is to fix this performance issue by loading the images dynamically and whenever we need it and also we can use features like placeholder or effect for our images to show the user a blurry effect or any picture we want when the images are too heavy and not ready to be loaded. &lt;br&gt;
We use React Lazy Load Image Component library like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8fl793avkfwhxr3nb8do.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8fl793avkfwhxr3nb8do.png" alt="React Lazy Load Image Component" width="800" height="650"&gt;&lt;/a&gt;&lt;br&gt;
You can checkout the whole document &lt;a href="https://www.npmjs.com/package/react-lazy-load-image-component" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, that's it! these were some of the coolest tips and techniques to improve our react projects' performance and have a better user experience. if you use them carefully, you are going to be much better react developer.&lt;/p&gt;

&lt;p&gt;This article can be called " Performance optimization tips " and also " React hooks : part 2 ".&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>performance</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Request easily, with Axios</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 27 Mar 2022 16:05:09 +0000</pubDate>
      <link>https://dev.to/samaghapour/request-easily-with-axios-5g3m</link>
      <guid>https://dev.to/samaghapour/request-easily-with-axios-5g3m</guid>
      <description>&lt;p&gt;Are you tired of catching errors with .catch methods?&lt;br&gt;
Are you tired of looooong API URLs and repeating headers for each request??&lt;br&gt;
Are you tired of not having an idea for handling fetch cancellation in useEffect cleanup???&lt;br&gt;
Are you tired of not having a good structure to manage your requests????&lt;/p&gt;

&lt;p&gt;Well, look who is here! Axios the savior…&lt;br&gt;
By using this lovely library, you don’t need the fetch() for requests anymore, and all the above problems will be solved.&lt;/p&gt;

&lt;p&gt;In this article, I will implement a good structure to manage requests using Axios and of course, I will explain how and why.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F0anw4ajjqstgr8nk03p3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F0anw4ajjqstgr8nk03p3.png" alt=" " width="473" height="715"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, I have used fetch() 3 times. Now let’s see the problems I got: 1. most parts of the request URLs are the same (Base URL) 2. I repeat the headers in all of them while they are completely identical 3. Instead of having one catch for all requests, I use the catch method for each request. if we got for instance 401 for each request they are not different, so why the catch method should be?&lt;br&gt;
This is the time that Axios comes up to the scene.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Axios installation
&lt;/h3&gt;

&lt;p&gt;npm install axios&lt;br&gt;
or&lt;br&gt;
yarn add axios&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Create a Services folder in the src folder
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F44j7yz6oau92z39gal2e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F44j7yz6oau92z39gal2e.png" alt=" " width="301" height="106"&gt;&lt;/a&gt;&lt;br&gt;
services folder contains 3 folders:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.Config folder which contains an index.js file that I put my initial config in.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;there is no doubt that I installed axios, but it is useless if I just want to use it without any config:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F6tr9l2widf4qfya7p8af.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F6tr9l2widf4qfya7p8af.png" alt=" " width="722" height="605"&gt;&lt;/a&gt;&lt;br&gt;
In the above example I used axios without config and you can see that I’m repeating myself with headers and baseUrls.&lt;/p&gt;

&lt;p&gt;Now this is what I put in src/Services/Config/index.js:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F63401wv490481o0y6tno.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F63401wv490481o0y6tno.png" alt=" " width="665" height="262"&gt;&lt;/a&gt;&lt;br&gt;
In the above code, axios.create, creates a new instance of axios and i can give it a custom config by passing an object as an argument of this create method.&lt;/p&gt;

&lt;p&gt;This config will apply to all requests made from the api instance and when I make a request with api, I don’t have to pass headers and base URL to each request and repeat myself.☺&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fhb74h61y6hs73fc1f050.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fhb74h61y6hs73fc1f050.png" alt=" " width="800" height="743"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, I comment out my previous requests(axios without config) and use my own instance named “api” and it does exactly the same thing&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fdyvflvcx6d5sqm8dsg4v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fdyvflvcx6d5sqm8dsg4v.png" alt="But better :)" width="781" height="661"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Attention to the above code example: the second parameter that I pass to post and put methods is the body and I can’t put it in the config, as you can see they are different bodies.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Tip: BaseURI is the address that gets attached to the beginning of the endpoints e.g: if the base URL is ‘&lt;a href="https://www.baseurl.com/api%E2%80%99" rel="noopener noreferrer"&gt;https://www.baseurl.com/api’&lt;/a&gt; , So api(‘/users/) will become api(‘&lt;a href="https://www.baseurl.com/api/users/%E2%80%99" rel="noopener noreferrer"&gt;https://www.baseurl.com/api/users/’&lt;/a&gt;)&lt;br&gt;
Tip:the headers that I used in my config has an authorization key with value of my token. i need this to be able to use api&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, now instead of Axios itself, I am going to use the api instance of Axios with my custom config.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.ErrorHandler folder which contains index.jsx file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fkiv4y1g8aurgefftd43w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fkiv4y1g8aurgefftd43w.png" alt=" " width="707" height="699"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes! this file is a jsx component, BUT, as you can see it returns nothing!&lt;/p&gt;

&lt;p&gt;We just need the function above which helps us to get rid of .catchs for each request(of course, you can handle Axios error catching with interceptors in different ways, but I am going to stick to my way).&lt;/p&gt;

&lt;p&gt;If you are not familiar with different error statuses, here are some good tips that you can read before investigating the above code:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Error 400: indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).&lt;br&gt;
Error 401: we need a token to set as authorization value in headers of our Axios instance config and when the user sign-in / sign up, the user receives a token and we set it to localStorage (or anywhere you want) and then set it to authorization of headers. It allows us to use API. But, tokens have an expiration time and when it gets expired or if we don’t set a token to our authorization at all, we are going to receive Error 401 that represented the request sent by the client to the server that lacks valid authentication credentials.&lt;br&gt;
Error 403: it means that accessing the page or resource you were trying to reach is absolutely forbidden for some reason.&lt;br&gt;
Error 404: indicates the server was unable to find what was requested. This message may also appear when the server is not willing to disclose the requested information or when the content has been deleted.&lt;br&gt;
Error 429: indicates the user has sent too many requests in a given amount of time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Interceptors&lt;/strong&gt;&lt;br&gt;
As you can see in the above example, we imported our Axios instance (named api) and used something named interceptors which there are two of them: the first interceptor is for requests and it does something with our request before we send it to the server and the second interceptor is for responses and it does something with the response before we get the response with .then and .catch methods.&lt;/p&gt;

&lt;p&gt;as you can see in the above example, we imported our Axios instance (named api) and used something named interceptors which there are two of them: the first interceptor is for requests and it does something with our request before we send it to the server and the second interceptor is for responses and it does something with the response before we get the response with “.then” and “.catch” methods.&lt;/p&gt;

&lt;p&gt;The “use” method of request requires two callbacks: the first one is the callback that gets triggered before the request is sent, and the second one is the callback that gets triggered when the request has an error.&lt;/p&gt;

&lt;p&gt;The “use” method of response requires two callbacks: the first one is the callback that gets triggered when our response status code lies within the range of 2xx(resolved or fulfilled), and the second one is the callback that gets triggered when our response status code falls outside the range of 2xx(rejected).&lt;/p&gt;

&lt;p&gt;In the example above, we used the response “use” method and passed a callback as the first parameter that does nothing special and just returns the response that it gets from the server without any change. BUT!, the second callback that we passed to the “use” method deals with errors and we do a lot of things with different errors instead of handling them in the “.catch” over and over again.&lt;/p&gt;

&lt;p&gt;Response error status codes usually are 400,401,403,404,429, and some other codes and we are going to handle them in this article but you can handle as many error status codes as you want :)&lt;/p&gt;

&lt;p&gt;The second callback of the ‘use’ method, receives an error as an argument, and this error argument has a response property which has a status property that we need, and other properties like data which has a message property that we need that.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: We return Promise.reject in all cases so that when the response goes through this step and goes to .then and .catch, the system knows the response is fulfilled or rejected to execute “.then” or “.catch” method.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In our example, we said…&lt;br&gt;
if the status code is 400, reject and then alert with the message of response itself.&lt;/p&gt;

&lt;p&gt;if the status code is 403, reject and then alert with the message of “you don't have permission…”&lt;/p&gt;

&lt;p&gt;if the status code is 404, just reject.&lt;/p&gt;

&lt;p&gt;if the status code is 429, reject and then alert with the message of “too many requests”&lt;/p&gt;

&lt;p&gt;If the status code is 401, we obviously don’t have a valid token( expired or doesn’t set at all), so we clear the whole information from the localStorage that we receive from the user when the user sign-up / sign-in. then we send the user to the login page to log in and set a new token to be able to use api.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Be aware you can be more creative and do things more than just an alert.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now in every file, you use this AxiosErrorHandler component, the interceptor has an eye on the api requests of that file and we don’t need to specify the same error handling in .catch methods multiple times.&lt;/p&gt;

&lt;p&gt;Well, I put AxiosErrorHandler component in “src/index.js” to have an eye on all the api requests I make in the whole project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fyiugdyl961l1l7940zpc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fyiugdyl961l1l7940zpc.png" alt=" " width="553" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.Requests folder contains all of our request actions in different category folders (The subject of the requests has different categories) for example:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fs1uq1sln0excuigmab86.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fs1uq1sln0excuigmab86.png" alt=" " width="135" height="133"&gt;&lt;/a&gt;&lt;br&gt;
The image above, is the content of Requests folder, each folder has a file named index.js: Auth folder’s index file contains all the requests related to authentication like login, register, forgotPassword,resetPassword,… :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fdz46bgbsezritb857iyk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fdz46bgbsezritb857iyk.png" alt="“Requests/Auth/index.js”&amp;lt;br&amp;gt;
" width="488" height="325"&gt;&lt;/a&gt;&lt;br&gt;
As you can see, we have different exported async functions for each request and in order to use it we just need to import and invoke it.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: remember these all are async functions and return response from the server, So we must use them asynchronously and receive the response and do whatever we want.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is another example for Blogs folder index file and as you have noticed it contains all requests related to blogs:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fgf3ce3nbir2mlslobsbq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fgf3ce3nbir2mlslobsbq.png" alt="“Requests/Blogs/index.js”" width="407" height="203"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fetch cancellation&lt;/strong&gt;&lt;br&gt;
Sometimes we use these fetch requests inside useEffect, but there is something you should know and that is useEffect invokes request action every time and even when the component gets unmounted and that’s the time you see this warning:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fy6l7s2qmhmp8wu5gtu6c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fy6l7s2qmhmp8wu5gtu6c.png" alt=" " width="498" height="157"&gt;&lt;/a&gt;&lt;br&gt;
To resolve this kind of warning, we just need to cleanup our requests whenever the component gets unmounted and we do this inside useEffect cleanup function ( the function that useEffect returns is the cleanup function as you are going to see in the example below) and there are few ways we can cancel a fetch requests inside cleanup function and for our case which is request with axios instance, this is very easy:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fkbwe750301aalgf04glz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fkbwe750301aalgf04glz.png" alt=" " width="800" height="280"&gt;&lt;/a&gt;&lt;br&gt;
You just need to create a controller instance and pass an object with a property named signal and the value of controller.signal as the api second parameter and then in the cleanup function all you have to do is to invoke the abort method of the controller and it will cancel the request when the component gets unmounted. now you are not going to receive that warning and your performance is better than before.&lt;/p&gt;

&lt;p&gt;This article ends here and hopefully you have learned how to use this lovely library to manage your requests as best as you can.&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>axios</category>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
    <item>
      <title>how does javascript Promise work under the hood?</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 27 Mar 2022 15:47:05 +0000</pubDate>
      <link>https://dev.to/samaghapour/how-does-javascript-promise-work-under-the-hood-4o4b</link>
      <guid>https://dev.to/samaghapour/how-does-javascript-promise-work-under-the-hood-4o4b</guid>
      <description>&lt;p&gt;hello friends😀&lt;/p&gt;

&lt;p&gt;I believe when we want to learn and conquer a programming language, we need to know how this language handles things under the hood to have a better understanding of what is going on and finally have fewer bugs when we use it.&lt;/p&gt;

&lt;p&gt;If you are like me then let’s start a new journey to learn everything about promises and see how Javascript handles Promises under the hood.😁&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Attention: if you don’t know anything about event loop, call stack, callback queue, and generally how javascript handles asynchronous operations under the hood which are this article’s Prerequisites, please learn them first, then come back to this article.&lt;br&gt;
You can learn about these requirements by clicking on &lt;a href="https://dev.to/samaghapour/how-javascript-asynchronous-works-under-the-hood-hln"&gt;this link&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;what are we going to investigate in this article:&lt;br&gt;
1.Everything about promises and why and how they are handled with real-world and code examples.&lt;br&gt;
2.Callbacks and callback hell&lt;br&gt;
3.Why did async come into being&lt;br&gt;
4.Microtask queue vs macrotask queue in javascript&lt;br&gt;
5.Async / await syntax sugar&lt;br&gt;
6.Debugging using try / catch / finally&lt;br&gt;
7.Promise.all() vs Promise.allSettled()&lt;/p&gt;

&lt;h3&gt;
  
  
  Promises in javaScript
&lt;/h3&gt;

&lt;p&gt;let’s start Promises with a real-world example:&lt;/p&gt;

&lt;p&gt;Imagine there is a boy who will celebrate his birthday two weeks from now and his mother promises him to bake a cake for his birthday. In these two weeks, the mother prepares stuff to bake a cake and the boy is not going to sit all week and wait for cake and then prepare the other stuff for the birthday party:\ because this way everything would be deferred because of one cake and it’s ridiculous. So at the same time, the boy is preparing other things for the party. Now until the cake is not baked, the mother’s promise’s state is ‘Pending’. When it’s done, the Promise’s state is going to be one of two states:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;fulfilled or resolved&lt;/li&gt;
&lt;li&gt;rejected
If the mother gets sick and can’t bake the cake (state: rejected), the boy is going to react (getting sad). But if the mother bakes the cake (state: fulfilled), the boy is going to react differently (getting happy), and no matter what state is rejected or fulfilled, the boy is going to have a party finally.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fufjh235mh2k9w46tlv43.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fufjh235mh2k9w46tlv43.png" alt=" " width="800" height="440"&gt;&lt;/a&gt;&lt;br&gt;
While the cake is being baked, the boy prepares other things for the party and this is an asynchronous operation because two things are happening at the same time.&lt;/p&gt;

&lt;p&gt;Javascript is a single-threaded language and it is synchronous which means it just can execute codes line by line and should wait for the execution to get finished to go to the next line. So how does it execute asynchronous operations like ajax requests?🤔 There is where Promises came to the scene.&lt;/p&gt;

&lt;p&gt;When javascript encounters ajax requests (like fetch), it knows that this is going to take a while to get the response, so javascript just returns an object until that data come and that this object is called Promise. In other words, javascript makes a promise that it is going to get something from the server as soon as possible and till that time it continues to execute the other lines instead of waiting for that data. now let’s check out what properties and methods this object includes:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fen6394s344rurr8qkuzz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fen6394s344rurr8qkuzz.png" alt=" " width="435" height="316"&gt;&lt;/a&gt;&lt;br&gt;
In the above image, we can see that the data variable which is a fetch request returning a promise object. This object includes:&lt;br&gt;
&lt;strong&gt;1.PromiseState property: its value can be one of three states:&lt;/strong&gt;&lt;br&gt;
+**“Pending” **when it is trying to get something from the server.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;“fulfilled”&lt;/strong&gt; when it gets data without an error.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;“rejected”&lt;/strong&gt; when it gets an error from the server.
&lt;strong&gt;2.PromiseResult property: its value gets changed depending on PromiseState value:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fw8hjuadg08r60plbp1ki.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fw8hjuadg08r60plbp1ki.png" alt="PromiseResult is undefined when the state is depending" width="435" height="316"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F7q41syyzq1lwuh9hs8n9.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F7q41syyzq1lwuh9hs8n9.jpeg" alt="PromiseResult is an error message when the state is rejected" width="650" height="282"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fm0edd14gmevu6h66jdux.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fm0edd14gmevu6h66jdux.png" alt="PromiseResult is the response that gets from the server when the state is fulfilled" width="479" height="472"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Prototype object: If you know about prototypes, then you have already guessed a prototype object is an object that consists of methods that ‘promise object’ inherited them. So these methods receive a function as a parameter (callback) and execute that function depending on promiseState property value:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.catch(): this method just executes its callback whenever the promiseState is ‘rejected’ and its callback receives a parameter which is the promiseResult value.&lt;/li&gt;
&lt;li&gt;.then(): this method just executes its callback whenever the promiseState is ‘fulfilled’ and its callback receives a parameter which is the promiseResult value.&lt;/li&gt;
&lt;li&gt;.finally(): this method executes its callback whenever the promiseState is either ‘rejected’ or ‘fulfilled’, in other words, if the PromiseState is not pending it executes the callback at the end anyway.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our first real-world example, the boy’s sadness is like the catch method executing its callback. The boy’s happiness is like the then method executing its callback, and having a party no matter the cake is baked or not, is like the finally method executing its callback.&lt;/p&gt;

&lt;p&gt;now let’s take a code example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fkxxeaqswdh8nw65x9bwz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fkxxeaqswdh8nw65x9bwz.png" alt=" " width="597" height="212"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, it is pending at first, then gets an error from the server (promiseState = ‘rejected’) and &lt;strong&gt;.catch()&lt;/strong&gt; method executes its callback, then &lt;strong&gt;.finally()&lt;/strong&gt; method executes its callback.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ff6k64uv2ouxrso6457l0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ff6k64uv2ouxrso6457l0.png" alt=" " width="800" height="186"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, it is pending at first, then gets the data from the server successfully (promiseState = ‘fulfilled’) and &lt;strong&gt;.then()&lt;/strong&gt; method executes its callback, then &lt;strong&gt;.finally()&lt;/strong&gt; method executes its callback.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are the callbacks? + how async operation came to being&lt;/strong&gt;&lt;br&gt;
In the above examples, we mentioned functions as the callback. So you may want to know what exactly is callback and why they exist?&lt;/p&gt;

&lt;p&gt;JavaScript is a single-threaded language and that is why it can’t execute more than one line of code at the same time and executing more than one line of code at the same time means asynchronous operation. So JavaScript had to wait a long time to get a response from a fetch request, and it blocks the code obviously, and that is why callbacks came to the scene to make JavaScript able to do an asynchronous operation.&lt;br&gt;
A callback is a function that is passed to a function as a parameter to get executed right after that function’s process is finished, and this is how asynchronous operation was born. By using a callback, javascript didn’t have to wait for something like an ajax request. Callbacks, get executed right after getting data from the server.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Attention: callbacks are not asynchronous and they are naturally synchronous. But they have the capability to enable JavaScript to handle async operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s take an example of callbacks:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fxzf70ac7a6m9g7yfmv2s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fxzf70ac7a6m9g7yfmv2s.png" alt=" " width="495" height="343"&gt;&lt;/a&gt;&lt;br&gt;
In the above example when the getData function was invoked, the second parameter (myCallback) is a function that is passed to getData as its callback, and it is going to execute that callback after getting a response from the fetch request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Callback hell&lt;/strong&gt;&lt;br&gt;
The problem with callbacks that causes Promises to come to the scene is something called Callback hell.&lt;br&gt;
Imagine if we wanted to do another async process inside a callback that was executed after the first async process and inside the second callback, we wanted to do another async process, and so on…&lt;/p&gt;

&lt;p&gt;This would end in &lt;strong&gt;nested callbacks&lt;/strong&gt; that are executed one after another and called &lt;strong&gt;callback hell&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fd7q27sszmg2cg737gzaf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fd7q27sszmg2cg737gzaf.png" alt="Callback hell" width="676" height="569"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, getData is my async function and I am calling it. After getting data, the callback is invoked and inside this callback, after logging the result, I invoke another async function as my second async function, and inside the second function’s callback, I keep doing the same process for 2 times more. As you can see I end up with nested callbacks that are hard to read and maintain. Imagine if I called more async functions inside callbacks. So I think you get the point :)&lt;br&gt;
In promises, we don’t need to do it inside each callback and instead, we have a cleaner and more readable async handler thanks to .then() and .catch() methods.&lt;/p&gt;

&lt;h4&gt;
  
  
  Promise chaining
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fsd8n773nods9fibuh13e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fsd8n773nods9fibuh13e.png" alt=" " width="447" height="430"&gt;&lt;/a&gt;&lt;br&gt;
Well, we said .then and .catch methods came to help our code to be more readable and more manageable. But if we perform the callback hell example with these methods like above, you can see we are returning promise after promise and after promise…&lt;br&gt;
And this chain of .then methods is called promises chaining. But what if there is something even much better than these methods that makes our code even more readable than it is now? :)&lt;/p&gt;

&lt;h4&gt;
  
  
  async / await syntax suger
&lt;/h4&gt;

&lt;p&gt;Javascript introduced async / await in ES8 which is syntax sugar for promises, which means it uses promises, and the only difference between using async / await and .then / .catch methods is their syntax. async / await makes asynchronous operations more like synchronous operations so it helps code readability much more than those methods.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fl70nsf2fvkrfkwfxtbkg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fl70nsf2fvkrfkwfxtbkg.png" alt="async / await" width="652" height="316"&gt;&lt;/a&gt;&lt;br&gt;
What is happening in the above example is the role of using async / await syntax:&lt;br&gt;
1.The function which is an async operation should have an &lt;strong&gt;async&lt;/strong&gt; word before it.&lt;br&gt;
2.The async request should have an &lt;strong&gt;await&lt;/strong&gt; word before it. This word stops the process inside the function(just inside) until the request is fulfilled or is rejected.&lt;br&gt;
3.Whatever we do after the await line, is happening &lt;strong&gt;right after&lt;/strong&gt; the request gets some result or error.&lt;/p&gt;

&lt;p&gt;The getData function is asynchronous itself and returns a promise and if all the async requests inside it are fulfilled, we can execute the .then() method on the getData function and if requests are rejected we can execute the .catch() method on the getData function, although this is unnecessary to use these methods with async function if we don’t need to do something after all requests.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fd590qiko94kt42vngzed.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fd590qiko94kt42vngzed.png" alt=" " width="800" height="364"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  try / catch / finally blocks for debugging and catching errors
&lt;/h4&gt;

&lt;p&gt;We can try our lines of codes and if there was an error we can catch it and either way we can do something finally:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F30oofoqgwko3hc2y1896.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F30oofoqgwko3hc2y1896.png" alt="try / catch / finally" width="800" height="504"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we put our requests inside the ‘try’ block and if there was an error, javaScript will stop continuing to execute codes inside the block and jump into the ‘catch’ block to show the error (the catch block receives a parameter which is the error) and after executing codes inside the catch block it will execute the ‘finally’ block. Even if there was no error, after the ‘try’ block it will execute the ‘finally’ block anyway.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Attention: when we use the try block we must use the catch block too. Otherwise, it’s not gonna work and throw an error, because after all, we are trying some codes to see if there is an error, catch it.&lt;br&gt;
But the ‘finally’ block is not necessary.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These blocks help us debug our codes better and they fill in for &lt;strong&gt;.then() and .catch() and .finally()&lt;/strong&gt; methods.&lt;/p&gt;

&lt;h4&gt;
  
  
  microtasks queue vs macrotasks queue
&lt;/h4&gt;

&lt;p&gt;In the “&lt;a href="https://dev.to/samaghapour/how-javascript-asynchronous-works-under-the-hood-hln"&gt;How javaScript Asynchronous works under the hood?&lt;/a&gt;” article, we learned that all synchronous tasks go to the call stack and callbacks go to web APIs until their time come to be executed and when that time come, the callback goes to the callback queue. of course, callback queue has some other names including task queue and &lt;strong&gt;Macrotask queue&lt;/strong&gt; which we call it macrotask queue in this article.&lt;br&gt;
you might say,well, what is new about it? 🤔&lt;/p&gt;

&lt;p&gt;there is another queue called &lt;strong&gt;microtask queue&lt;/strong&gt;.😀I want to talk about this queue in this article because the microtask queue is related to promises and this is the right place to explore it.&lt;/p&gt;

&lt;p&gt;The point is that all callbacks don’t go to the macrotask queue :&lt;br&gt;
1.The callbacks that are scheduled like setTimeout and setInterval and event handler callbacks go to the &lt;strong&gt;macrotask queue&lt;/strong&gt;.&lt;br&gt;
2.The callbacks that are meant to be executed right after the asynchronous operation like callbacks of .then() .catch() methods, go to the &lt;strong&gt;microtask queue&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now let’s see the priority of the event loop and which codes the event loop executes first:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;event loop first priority is call stack which consists of synchronous codes&lt;/li&gt;
&lt;li&gt;the second priority is the microtask queue which consists of promise callbacks&lt;/li&gt;
&lt;li&gt;the third priority is the macrotask queue which consists of scheduled callbacks
the below gif shows these priorities very clear:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Flnmm5pzbdhlww59txx7f.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Flnmm5pzbdhlww59txx7f.gif" alt=" " width="760" height="427"&gt;&lt;/a&gt;&lt;br&gt;
Now, let me ask you a question. What is the result of the code below?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F5rh67wss9i1qdke77gdv.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F5rh67wss9i1qdke77gdv.jpeg" alt=" " width="305" height="213"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The answer:&lt;br&gt;
1.The first line goes to call stack,because it’s synchronous code.&lt;br&gt;
2.Next line goes to web APIs and after 0 mili second, it goes to macrotask queue.&lt;br&gt;
3.Next line goes to web APIs and after promise is resolved, it goes to microtask queue.&lt;br&gt;
4.Next line is synchronous code again. so it goes to call stack.&lt;/p&gt;

&lt;p&gt;Now event loop , executes the call stack tasks first which is “Start!” and then “End!”. now call stack is empty, so event loop executes the microtask queue’s callbacks which is “Promise!” and after microtask queue if this queue is empty, it is time for macrotask queue, so setTimeout callback gets executed which is “Timeout!”. let’s see the all operation in the gif below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F0zh0ei6uayhrghain1z6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F0zh0ei6uayhrghain1z6.gif" alt=" " width="760" height="427"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promise constructor&lt;/strong&gt;&lt;br&gt;
There will be some times you want to instantiate a Promise object so in order to complete this article let’s just take a look at how it works:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fyeh72zu0wsxqqyymg4ak.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fyeh72zu0wsxqqyymg4ak.png" alt=" " width="800" height="159"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we instantiate a promise which is going to return ‘resolved data’ as a promiseResult with the fulfilled state.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8oh48091ihvgt5i76mi4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8oh48091ihvgt5i76mi4.png" alt=" " width="800" height="169"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we instantiate a promise which is going to return ‘Error : rejected’ as a promiseResult with the rejected state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promise.all() vs Promise.allSettled()&lt;/strong&gt;&lt;br&gt;
In some cases, you may have an array of asynchronous requests that you want to take care of, all-in-one, and receive the array that includes the responses for each request. You can use the Promise.all() method that takes one parameter which is an array of requests and if all of that requests’s state is fulfilled, it returns an array of responses:&lt;br&gt;
&lt;a href="https://media2.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%2F4u7uwi9vur9n2xrl8o9h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F4u7uwi9vur9n2xrl8o9h.png" alt=" " width="800" height="195"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now if just one of our requests is rejected, Promise.all() is going to return just an error of that rejected request. In other words, this method is ‘all or nothing’:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fw5y1y63ktbjbt02m2zj3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fw5y1y63ktbjbt02m2zj3.png" alt="the secondData is going to be rejected" width="800" height="137"&gt;&lt;/a&gt;&lt;br&gt;
In order to fix this ‘all or nothing problem, dear javascript gives us another method called Promise.allSettled() which does the same process that promise.all does but the difference is allSettled method returns an array of objects for each request that includes two properties, ‘status’ which is the state of that request, and ‘value’ which is the result of that request, and ‘reason’ which takes the ‘value’ property’s place if the request is rejected. It is not going to give up all the responses just because one of the requests is rejected:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ffny6g4noyjhj8mvw6c7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ffny6g4noyjhj8mvw6c7b.png" alt="the secondData is rejected" width="800" height="298"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This article ends here and hopefully you learned everything about promises and its complements in javaScript.&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>promise</category>
      <category>programming</category>
    </item>
    <item>
      <title>oop in javascript! part2:4 pillars of oop</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 27 Mar 2022 14:38:52 +0000</pubDate>
      <link>https://dev.to/samaghapour/oop-in-javascript-part24-pillars-of-oop-1lfp</link>
      <guid>https://dev.to/samaghapour/oop-in-javascript-part24-pillars-of-oop-1lfp</guid>
      <description>&lt;p&gt;Hi everyone 😃&lt;/p&gt;

&lt;p&gt;In the previous article, we started a journey to the oop world by learning prototypes and classes and in this article, we are going to end this journey by exploring 4 pillars of object-oriented programming.&lt;br&gt;
But before we start, what is object-oriented programming?🤔&lt;/p&gt;

&lt;p&gt;OOP is a paradigm of programming based on objects (blueprint) that gather related data together and we can instantiate that object and create other objects (instances) and we learned about them in the previous article.&lt;/p&gt;

&lt;p&gt;If I want to give an example of an object in the real world, a Car is an object that includes properties like wheels, doors, steering wheel, and methods like moving, stopping, etc… one other example is a person is an object that includes properties and methods like height, weight, skin color, name, age, etc…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F0r58d54lesj8d1okng8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F0r58d54lesj8d1okng8h.png" alt=" " width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Encapsulation:&lt;/strong&gt;&lt;br&gt;
This pillar is about gathering the related data (properties, methods) inside one object So that nothing unrelated can access (read or modify) that data directly.&lt;br&gt;
For example, we have a lot of related data, including start, stop, blowHorn, etc… Which are broadcasted on the global scope and can be accessed by anything, so what we can and should do is to wrap them with an object called Car and that way, something like cow can’t access the blowHorn property! :|(I’m sure you get what I mean and may have better examples in your exploratory minds)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fax37d1gwac2kiavmxtlu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fax37d1gwac2kiavmxtlu.png" alt=" " width="399" height="368"&gt;&lt;/a&gt;&lt;br&gt;
As we can see in the example above, in a bad way, I spread the data in the global scope and anything can just call start or blowHorn and that is not something oop would be happy about.&lt;br&gt;
In a good way (encapsulation), I wrapped these related data with one object called Car so that to tell anyone you are not allowed to use these methods for something like greeting!&lt;br&gt;
In other words, encapsulation is about building a shield to protect related data by preventing them from being directly accessed anywhere and it makes special methods called getter and setter to get and set these data. Of course, I didn’t mention these methods in the above example, so let’s see another example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F4dqtoed0wv6d4hfyxdys.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F4dqtoed0wv6d4hfyxdys.png" alt=" " width="529" height="646"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, if I didn’t encapsulate data, they would be accessible anywhere.&lt;br&gt;
By putting them inside Car class, I make them protected and safe. So now I know what these name and speed properties are for and how to set and get them by calling getName and setName, etc…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fuxknc0dlxbzctjwzqzxv.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fuxknc0dlxbzctjwzqzxv.jpeg" alt=" " width="800" height="600"&gt;&lt;/a&gt;&lt;br&gt;
In the above image, you see an example of a car in the real world. A car is an object that includes wheels, engine, body, and methods like move and shutDown and etc… and we just need to call them.&lt;br&gt;
conclusion: encapsulation redusing the complexity by gathering the related data in one object and protecting the data from being accessed by the outer scope to make them safe.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Abstraction&lt;/strong&gt;&lt;br&gt;
This concept is about hiding unnecessary data and just showing the essentials. It means you don’t need to know how that method works, you just need to know what it does.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fvjzzazaxusqq9jieoaoc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fvjzzazaxusqq9jieoaoc.png" alt=" " width="603" height="392"&gt;&lt;/a&gt;&lt;br&gt;
In the above picture, that dude doesn’t think about how his machine moves when he presses the accelerator pedal, he just knows by pressing that pedal (by calling move method) the machine is going to move.&lt;br&gt;
code example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fo852w6cueiwxkbu2p8cd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fo852w6cueiwxkbu2p8cd.png" alt=" " width="633" height="746"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we know what the start method does, but we don’t care about how it does it, and that is the abstraction.&lt;br&gt;
One other thing to talk about in the above example is throwing errors in some methods which means you can’t use this method without overriding it for each instance, and also you can’t instantiate the Car object and you just can instantiate its children classes. but why should we override some methods?🤔&lt;/p&gt;

&lt;p&gt;well that’s a good question and the answer is :&lt;br&gt;
Imagine we have a method like a start that doesn’t need to be overridden and it is the same in all instances. But if we want to change the start functionality in the Tesla object, we have to change this method from the Car object and this change will impact all other children objects’ start method but we wanted just to change it for Tesla. And that is the reason we override the getPower method for each class child in the above example. Because getPower has a different implementation for each car. Tesla needs electricity but Volvo needs petrol.&lt;/p&gt;

&lt;p&gt;conclusion: abstraction shows the essentials and hides the Inessential data in order to reduse the complexity, isolates impact of changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.Inheritance&lt;/strong&gt;&lt;br&gt;
This concept is about creating a class with a lot of methods and properties to be inherited and used by other classes which have their own special data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F4mstqm399gdepoo559eq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F4mstqm399gdepoo559eq.png" alt=" " width="309" height="161"&gt;&lt;/a&gt;&lt;br&gt;
In the above image, we have a Car object that includes properties like door, wheel, and methods like move, stop, blowHorn, etc… and for building different cars we don’t invent the wheel again! Or other methods we mentioned, we just inherit them from the Car object and define other special properties for each car object like color or power, etc…&lt;br&gt;
code example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F2jdvio63odrclou63dhz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F2jdvio63odrclou63dhz.png" alt=" " width="800" height="603"&gt;&lt;/a&gt;&lt;br&gt;
In the above example, we have a Car object that includes methods like start and stop. And we have other classes named Tesla and Volvo with special getPower method and inherited methods from Car object to not define them from zero again. Now we can have different models of Tesla and Volvo by instantiating Tesla and Volvo classes.&lt;/p&gt;

&lt;p&gt;We didn’t define a start method for each object but when we call it on each instance it knows what to do because it inherited it from the Car object.&lt;/p&gt;

&lt;p&gt;conclusion: inheritance prevents duplication methods and occupying more memory space, makes methods reusable and reduses the complexity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.Polymorphism&lt;/strong&gt;&lt;br&gt;
polymorphism consists of two words, poly means ‘many’ and morph means ‘form’ ,thus it means many forms. This concept is about making methods overridable so when we inherit methods, we can override the method which we need, instead of defining a new method and allocating more memory space. In other words, it means the output of our inherited method can have many forms for each object without duplicating them.&lt;br&gt;
If you duplicate the method for each object, in addition to occupying more memory space, decreasing performance and complexity, it ruins the maintainability of the code. So when you want to change that method a little bit, you have to change it in all objects one by one. My fingers get numb even with think of it 😖&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ftxw50p7i5pebsm04gepr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ftxw50p7i5pebsm04gepr.png" alt=" " width="300" height="168"&gt;&lt;/a&gt;&lt;br&gt;
In the above image, all cars inherit the steering wheel but with different implementation(different form).&lt;br&gt;
code example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fxm9zr2xemri12ep4a191.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fxm9zr2xemri12ep4a191.png" alt=" " width="479" height="690"&gt;&lt;/a&gt;&lt;br&gt;
I don’t think it needs more explanation.&lt;/p&gt;

&lt;p&gt;conclusion: polymorphism prevents duplicating methods and memory space occupation by giving methods the capability to be overridden. Causes performance improvement, increases code readability and maintainability, and reduses the complexity.&lt;/p&gt;

&lt;p&gt;Well, you may have some questions like what is the difference between abstraction and encapsulation, abstraction and inheritance, etc… So it is understandable to have those questions because they all take advantage of each other. For example, polymorphism uses the inheritance concept.&lt;br&gt;
These questions even may be asked in interviews, and the answer is it doesn’t matter how similar they are to each other. The difference between them is their special way of reaching a common goal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Encapsulation&lt;/strong&gt; way: gathering related data in one object and protecting them from being directly accessed by the outer scope.&lt;/p&gt;

&lt;p&gt;**Abstract **way: Hide unnecessary data and display essential data to reduce complexity. And isolate the impact of change.&lt;/p&gt;

&lt;p&gt;**Inheritance **way: inheriting the methods and properties to make them reusable. And prevent duplication methods and more memory space occupation.&lt;/p&gt;

&lt;p&gt;**Polymorphism **way: overriding inherited methods for each object without duplicating methods. And increases performance and code readability and maintainability.&lt;/p&gt;

&lt;p&gt;You may have noticed the common goal between those 4 pillars which is reducing complexity and that is object-oriented programming: writing our code simple and reusable and less complex based on objects.&lt;br&gt;
This journey ends up here and I hope you’ve learned oop in javascript once and for all.&lt;/p&gt;

&lt;p&gt;Goodbye and Good luck 🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>oop</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>oop in javascript! part1: prototype</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 27 Mar 2022 10:30:17 +0000</pubDate>
      <link>https://dev.to/samaghapour/oop-in-javascript-part1-prototype-55ie</link>
      <guid>https://dev.to/samaghapour/oop-in-javascript-part1-prototype-55ie</guid>
      <description>&lt;p&gt;Hello friends😀&lt;br&gt;
When I was learning Javascript, I’ve always wondered when I define a string or function, etc… how is it possible to get some properties and methods like length or search or forEach or any other methods?? When we see the backstage, we realize where all these come from. Finally, we find out a little bit about oop in javascript and what exactly is going on under the hood.&lt;br&gt;
So we’ll explore oop in javascript in two parts. The first part is going to be about the prototype and setup for oop and the second part is just all about oop in javascript.&lt;br&gt;
Javascript is an object-based language based on prototypes in contrast to other languages which are class-based.&lt;br&gt;
This causes the Javascript object hierarchy and inheritance a little bit weird and complex. But what exactly are prototypes?&lt;br&gt;
Let’s begin our journey with a simple example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fym0sgne9mkfmojegp1cz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fym0sgne9mkfmojegp1cz.png" alt=" " width="607" height="200"&gt;&lt;/a&gt;&lt;br&gt;
Here, I declared an object and logged its three properties, But wait a minute! I just declared a name and age property, where the hell is that hasOwnProperty method(object property which is a function called method) coming from? Hmmm…🤔 let’s log the whole object itself to see what it includes:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fma6gno7w3kn9fw3ekojr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fma6gno7w3kn9fw3ekojr.png" alt=" " width="476" height="111"&gt;&lt;/a&gt;&lt;br&gt;
Well well well, look who’s here, now we can see when we define an object, javascript gives it a hidden but accessible property which is an object and called &lt;strong&gt;proto&lt;/strong&gt;. Now let’s take a look at the &lt;strong&gt;proto&lt;/strong&gt;_ property:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8tvg6zy3j277h68ixk4g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8tvg6zy3j277h68ixk4g.png" alt=" " width="800" height="269"&gt;&lt;/a&gt;&lt;br&gt;
Here is where we can see the hasOwnPropert method and some other methods as well. The interesting thing is if we define thousands of objects with millions of properties, there is still going to be one more default property in all of them which is this object with all these methods and this object called ‘Global object prototype’ and what is more interesting is javascript is not going to define or in other word duplicate this object for every object we define, it is just going to give them &lt;strong&gt;proto&lt;/strong&gt; property that references to global object prototype and in other word inherit global object prototype, so it will ensure to not blow up memory and what is much more interesting is if we look at global object prototype, it has &lt;strong&gt;proto&lt;/strong&gt; property itself! Although it is null and kind of a reference to a dead-end, the point is there is no object that doesn’t have &lt;strong&gt;proto&lt;/strong&gt;. Javascript is full of interesting things :)&lt;br&gt;
Let’s investigate proto with different ways:&lt;/p&gt;

&lt;h4&gt;
  
  
  Object literal using object.create and object.setPrototypeOf methods
&lt;/h4&gt;

&lt;p&gt;*&lt;em&gt;1. using object.create: *&lt;/em&gt; **&lt;br&gt;
&lt;a href="https://media2.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%2Fm8igyab9mjytuc1op8lf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fm8igyab9mjytuc1op8lf.png" alt=" " width="662" height="312"&gt;&lt;/a&gt;&lt;br&gt;
So, we have a Car object with three properties or methods and nothing else. Then we declared a tesla variable and assigned it to object.create with 2 parameters, which is a Car object and the second parameter is an object with name property and value of tesla(it is a simple object but with a different shape of defining inside object.create), Let’s log tesla variable and see what object.create does:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fbdrpe5tyory19apib779.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fbdrpe5tyory19apib779.png" alt=" " width="640" height="441"&gt;&lt;/a&gt;&lt;br&gt;
As we can see, object.create defines an object with a name property and value of tesla using the second parameter, and this object’s &lt;strong&gt;proto&lt;/strong&gt; is referred to the object we gave in object.create’s first parameter(which is Car object in this example) and the proto of the Car object is referred to global object prototype and proto of global object is referred to as null.&lt;br&gt;
&lt;strong&gt;object prototype chaining&lt;/strong&gt;&lt;br&gt;
Remember, all prototypes are connected, no matter how nested they are going to be, at the end it comes to the global object prototype and then null and this is called object prototype chaining.&lt;br&gt;
the second variable we defined is detail, Let’s just log it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F9n6fmycqvwpuy9ha2k66.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F9n6fmycqvwpuy9ha2k66.png" alt=" " width="550" height="469"&gt;&lt;/a&gt;&lt;br&gt;
It is an object with its special property called speed and value of 3001, and its proto is referred to tesla, as you can guess from the example picture, and tesla’s proto is referred to Car object and Car object’s proto is referred to global object prototype and that is the prototype chaining.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prototypal delegation&lt;/strong&gt;&lt;br&gt;
if you pay more attention to the example, you can see that detail can access to the name property of tesla object and car object but tesla can’t have access to detail’s speed property, and it’s because they only can have access or inherit objects that their prototypes are referred to. and it is a top to bottom relationship called Prototypal delegation.&lt;/p&gt;

&lt;p&gt;so when we log tesla.speed, javascript is going to look for it inside the tesla object and if not find it, it will look for it inside its proto which is Car object and if there is no such property, it will keep looking for it inside other proto on the prototype chain which is global object prototype and if it isn’t there too, it will give us an undefined.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;reason of annoying error known as ‘ ** is not a function’&lt;/strong&gt;&lt;br&gt;
As I explained above, when javascript can’t find a property inside the prototype chain, it returns an undefined. But if the speed property was a function (method) instead of number and javascript can’t find it, it will return an error &lt;strong&gt;'tesla.speed is not a function'&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;so when we call some methods on arrays or functions and javascript can’t find them, it returns an error and I’m sure you were in that situation that keep getting ‘ * is not a function’ before.&lt;br&gt;
the third variable called volvo is going to have the same process as tesla has and the difference between volvo and tesla is just the name property’s value is volvo:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fwnzxqc2q6vyn04s3btzu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fwnzxqc2q6vyn04s3btzu.png" alt=" " width="624" height="434"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  *&lt;em&gt;2.using object.setPrototypeOf: *&lt;/em&gt; **
&lt;/h4&gt;

&lt;p&gt;three variables (tesla,detail,volvo) that we defined above can be defined using object.setPrototypeOf( ) method:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F01j4f26rbsz0nnnnsfzh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F01j4f26rbsz0nnnnsfzh.png" alt=" " width="647" height="329"&gt;&lt;/a&gt;&lt;br&gt;
In this use case, we define an object with its special property and value. Then object.setPrototypeOf’s first parameter selects the object which we want to manipulate its proto reference, and the second parameter is the object we want proto to be referred to.&lt;/p&gt;

&lt;p&gt;So in the above image, we select tesla and set its proto reference to Car object, select detail object and set its proto to tesla object, and then volvo object’s proto to Car object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constructor function using new keyword&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fkpv2y7xjkfg7k7p8cm6c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fkpv2y7xjkfg7k7p8cm6c.png" alt=" " width="512" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Functions are function and object!&lt;/strong&gt;&lt;br&gt;
Functions can behave like an object because when we define them, javascript gives them a bunch of methods and properties, and as you can see, I defined a Car function and gave it name property.&lt;/p&gt;

&lt;p&gt;Now let’s investigate the above image:&lt;/p&gt;

&lt;p&gt;When there is a function whose name is capitalized and it has the ‘this’ keyword inside, we tell javascript that this is an object and can be instantiated by using the new keyword. By putting ‘this’ inside the constructor function, we tell javascript every object that has instantiated from this function ‘this’ will be referred to as that object.&lt;/p&gt;

&lt;p&gt;In the example above, defining tesla with the new keyword and Car() function and ‘ this.name ‘ inside Car function is something like “hey javascript, tesla should have a name property and its value should be whatever it passes as an argument, as well as volvo.”&lt;/p&gt;

&lt;p&gt;The car function is called the Constructor function.&lt;/p&gt;

&lt;p&gt;Hey, we missed that prototype part, what about that????🤔&lt;/p&gt;

&lt;p&gt;In the above example, we are manipulating the Car object’s proto. So when Car becomes any object’s proto’s reference, it is going to be an object containing those methods that we gave to the Car prototype.&lt;br&gt;
Note that name is not in proto object, name is something we need to give to each object we defined with its special value.&lt;br&gt;
Let’s log tesla and see the result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fp33apdsl0n1lew87ou5q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fp33apdsl0n1lew87ou5q.png" alt=" " width="580" height="448"&gt;&lt;/a&gt;&lt;br&gt;
When we instantiated the Car as tesla, we created the object with the name property and value of tesla and its proto is referred to Car prototype which is an object with three methods that we defined and this object is referred to global object prototype. the same process is true about volvo.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note that without new keyword we can’t instantiate constructor function and new keyword is the one who creates an object and refers “this” keyword to object that it created and adds Car’s prototype to object’s proto that it created.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Now the main reason why we have prototypes?&lt;/strong&gt;&lt;br&gt;
Imagine we want to declare thousands of objects with name property and some methods that all of them should have and all of those methods are doing the same thing as other objects’ methods.&lt;br&gt;
Do you think it is a good idea to declare all of those objects one by one and define all those methods one by one for every object? Hell no! this will kill the memory.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F2xy4pzj1uqrcd0eq15qe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F2xy4pzj1uqrcd0eq15qe.png" alt=" " width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;by using constructor function and prototypes we just have to declare one object with all methods we need and let other objects just inherit these methods and use them.&lt;/p&gt;

&lt;p&gt;in the above example we are not declaring volvo object and tesla object and each of them with three methods, we just instantiate Car and inherit methods from it.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;note that ‘this’ keyword inside sayName method is referred to the object that inherit it.&lt;br&gt;
note that in above example at last line, we are logging tesla.noneFunction method, So javascript is going to look for it in its prototype chain and if not find it, will return ‘tesla.noneFunctoin is not a function’.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and yes! Global object prototype is one prototype object containing methods for all objects in javascript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;difference between &lt;strong&gt;proto&lt;/strong&gt; and prototype&lt;/strong&gt;&lt;br&gt;
We have gone so far, I’m not going to leave you with this question without an answer. Although you may have already noticed the difference.&lt;br&gt;
Prototype just exists on a function and is defined as a property when a function is declared. A prototype is just an object of methods we give to the constructor function as a reference for its instance object’s &lt;strong&gt;proto&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fk123h6breydbkbv3ndiu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fk123h6breydbkbv3ndiu.png" alt=" " width="800" height="458"&gt;&lt;/a&gt;&lt;br&gt;
as we can see Car.prototype is the same tesla.&lt;strong&gt;proto&lt;/strong&gt; , because tesla is an instance of the Car and its proto is referred to Car.prototype.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;proto&lt;/strong&gt; for objects and prototype for functions.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;ES6 classes using the new keyword&lt;/strong&gt;&lt;br&gt;
Now, we are getting closer to the oop area… In many programming languages, we have a concept called oop or object-oriented programming which is a paradigm for designing programs using classes and objects.&lt;br&gt;
Classes are introduced in ES6 and made Javascript able to use oop, but it just fakes it and makes it look like oop, but it is totally different under the hood and javascript uses the same prototype process we already knew about it. In other word, javascript has oop but in its own way:)&lt;br&gt;
Now, let’s see the prototype process with classes and new syntaxes to get a better understanding of what oop looks like and how the prototype and inheritance process happen:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Faywyeziwbvtv4ytsi5dr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Faywyeziwbvtv4ytsi5dr.png" alt=" " width="703" height="708"&gt;&lt;/a&gt;&lt;br&gt;
I declared a class called Car, and inside this class, we have a constructor. This is the same constructor function we saw earlier:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F7dqepq1rh4uuyf9hdz5t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F7dqepq1rh4uuyf9hdz5t.png" alt=" " width="380" height="276"&gt;&lt;/a&gt;&lt;br&gt;
And the methods we declared inside Car class, is like we set the prototype of Car to some methods but more easily and cleanly:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fi0m1wfq8j8616dons2jp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fi0m1wfq8j8616dons2jp.png" alt=" " width="534" height="468"&gt;&lt;/a&gt;&lt;br&gt;
Now Let’s talk about this part:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fcfdkmzkb7e5y48p9o6ei.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fcfdkmzkb7e5y48p9o6ei.png" alt=" " width="688" height="470"&gt;&lt;/a&gt;&lt;br&gt;
Well, you already know the ‘new’ keyword and what it does.&lt;/p&gt;

&lt;p&gt;It instantiates Car and creates a new object with name property and value of tesla, and a proto object which is referred to an object containing those three methods that we declared inside Car class and another &lt;strong&gt;proto&lt;/strong&gt; object that is referred to Global object prototype… same for volvo.&lt;/p&gt;

&lt;p&gt;Then, we declare another class called Detail with its special property named speed and by using extends and super() we inherit all things inside Car class including name property and proto object of three methods.&lt;/p&gt;

&lt;p&gt;Here is the result of logging the detail object that is instantiated from the Car object:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fxl4sm1yxqga1j2dcrm0l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fxl4sm1yxqga1j2dcrm0l.png" alt=" " width="532" height="515"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is how javascript implements oop :)&lt;/p&gt;

&lt;p&gt;We learned about the prototype and what it is and how you can take advantage of it in many different ways in javascript.&lt;/p&gt;

&lt;p&gt;In the next part, we will explore the four pillars of oop and all the things we need to know with real-world and code examples.&lt;/p&gt;

&lt;p&gt;Until the next part, Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>oop</category>
      <category>prototype</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Understanding hoisting,scopes, and closures in JavaScript</title>
      <dc:creator>Sam aghapour</dc:creator>
      <pubDate>Sun, 27 Mar 2022 09:40:47 +0000</pubDate>
      <link>https://dev.to/samaghapour/understanding-hoistingscopes-and-closures-in-javascript-3337</link>
      <guid>https://dev.to/samaghapour/understanding-hoistingscopes-and-closures-in-javascript-3337</guid>
      <description>&lt;p&gt;hi everyone😀&lt;/p&gt;

&lt;p&gt;there are a bunch of important concepts in javaScript that you should know as a JavaScript developer and today we’re gonna explore some of those concepts including “Scopes and closures and hoisting”.&lt;br&gt;
I do my best to make it simple and as brief as possible, so let’s dive in.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1.Scopes&lt;/strong&gt; **
&lt;/h2&gt;

&lt;p&gt;what is scope anyway?&lt;br&gt;
the scope is an area where variables, functions, and classes are accessible in.&lt;br&gt;
scopes in javaScript&lt;br&gt;
we have 2 types of scopes in JavaScript:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Global Scope&lt;/li&gt;
&lt;li&gt;Local scope
the variables that are declared inside a function are in the local scope (function scope) and the ones that are declared outside of a function are in the Global scope.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Global Scope&lt;/strong&gt;&lt;br&gt;
when you start declaring a variable outside of any function, it’s in Global scope and can be accessed everywhere (even in local scope) :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fzz1z13g9ijhesqkawqjk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fzz1z13g9ijhesqkawqjk.png" alt=" " width="754" height="744"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Local scope&lt;/strong&gt;&lt;br&gt;
when you declare a variable inside functions curly brackets, this variable is in Local scope and belongs to that area, it is not accessible outside of local scope (outside of the curly brackets including global scopes and other local scopes ) :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8iiuikw4ue2sbm8jxtci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8iiuikw4ue2sbm8jxtci.png" alt=" " width="734" height="894"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;note there is an exception for this accessibility in other local scopes which we’ll talk about it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Block Statement&lt;/strong&gt;&lt;br&gt;
there is something you should know and that is the “switch and if conditions”,” for and while loops” areas does not have a special local scope like functions and any variables declared inside these scopes are belong to and accessible in the scope which these loops or conditions are defined:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F1ug2h6h7pc9dpf0sqpnq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F1ug2h6h7pc9dpf0sqpnq.png" alt=" " width="754" height="782"&gt;&lt;/a&gt;&lt;br&gt;
ECMAScript 2015(ES6) introduced two new keywords for declaring variables: let and const which have some differences from the var keyword and one of these differences that is good to be mentioned here is:&lt;br&gt;
when we declare a variable with var keyword inside loops and condition curly brackets it’s accessible in the outer scope as we have seen before, but when declaring the variable with let or const keyword it is accessible inside that curly brackets and nowhere else! :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fnopzhng3sfndumzmrgo7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fnopzhng3sfndumzmrgo7.png" alt=" " width="754" height="1490"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lexical Scope&lt;/strong&gt;&lt;br&gt;
as I mentioned above, variables inside the local scope are just accessible inside that scope and not in the global scope or any other local scopes but there is an exception for this accessibility in other local scopes.&lt;br&gt;
this exception belongs to this subject “The Lexical Scope (or Static Scope)”, but what is lexical scope?!&lt;br&gt;
the lexical scope can be found in many programming languages and if I want to be brief: when we define a function inside a function, the inner function (or child function) has access to its parent function’s scope too, in another word if we have many nested functions, the child functions have access to their parent's scope too.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fllklppywy5xm38b3ozac.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fllklppywy5xm38b3ozac.png" alt=" " width="800" height="672"&gt;&lt;/a&gt;&lt;br&gt;
in the example above, you can see child function has access to all variables inside its parent's scope, and parent has access to grandfather’s scope but something interesting you may notice, is these accessibilities are top to bottom and parents can not have access to their children's scope.&lt;br&gt;
so this is the Lexical Scope or Static Scope&lt;br&gt;
&lt;strong&gt;Dynamic Scope&lt;/strong&gt;&lt;br&gt;
we have talked about static Scope, so it is not fair to leave Dynamic Scope behind without saying a word about it&lt;br&gt;
I want to explain Dynamic scope with this example and compare it with static scope:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Ffjlmdamlquj1nltyed8c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Ffjlmdamlquj1nltyed8c.png" alt=" " width="800" height="804"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example, there is an “a” function declared in the global scope and “b” function that includes ‘someVar’ variable with the value of 1 and a is invoked inside this local scope, and in global scope, we have the same someVar variable with different value of 0 and b is invoked, now what is gonna happen?is “a” function gonna log 0 as ‘someVar’ variable value? or 1?&lt;br&gt;
well, that is the place that shows the differences between static and dynamic scopes.&lt;br&gt;
in static scope: when “someVar” can’t be found in “a” local scope, javaScript is gonna look for it inside the scope that “a function has been declared “ it means global scope in this case and the value will be 0.&lt;br&gt;
in dynamic scope: when “someVar” can’t be found in “a” local scope, javaScript is gonna look for it inside the scope that “a function has been invoked “ it means local scope (b function scope) in this case and the value will be 1.&lt;br&gt;
summary of this comparison:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;in lexical scope it looks for missing variable in scope that the function has been declared.&lt;/li&gt;
&lt;li&gt;in dynamic scope it looks for missing variable in scope that the function has been invoked.
it’s done! let’s go for closures🤠&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2.Closures&lt;/strong&gt; **
&lt;/h2&gt;

&lt;p&gt;closure feature in js is about the capabilities of the inner function to accessing their parent functions scope which we already know some things about it, but the main usabilities of this feature have left.&lt;br&gt;
thus, a closure is a function defined in other function scope and this closure function has access to three scopes (scope-chain):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;its own local scope&lt;/li&gt;
&lt;li&gt;its parents scopes&lt;/li&gt;
&lt;li&gt;the global scope&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Funl77cxe3v22jtiishne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Funl77cxe3v22jtiishne.png" alt=" " width="634" height="894"&gt;&lt;/a&gt;&lt;br&gt;
I’m sure you know that the inner function is the closure in the above example that is declared inside the outer function scope and besides its own ‘a’ variable, it has access to the ‘b’ variable of the outer scope.&lt;br&gt;
note: variables lifespan inside a function scope begins when the function gets invoked and when the function execution gets finished, variables inside it are all gonna get cleaned like there was no variable like that.&lt;br&gt;
so with this note let’s explore the above example step-by-step and see what is happening:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;function outer includes ‘b’ variable with the value of 50 and returns an inner function (note it returns function itself and not the function output)&lt;/li&gt;
&lt;li&gt;function inner is a closure and includes ‘a’ variable with the value of 30 and has access to ‘b’ variable and logs a + b (30+50).&lt;/li&gt;
&lt;li&gt;when we define x with outer(), now x is the same closure function and can be invoked:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fjnd3pezxyf37j468iqmd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fjnd3pezxyf37j468iqmd.png" alt=" " width="684" height="520"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;as soon as we define x = outer function, outer get execute and b variable inside it, is declared and after finishing the execution, b has been eliminated now, so when we call x(), how x is gonna find b value?&lt;/li&gt;
&lt;li&gt;when javaScript looks for ‘b’ and can't find it, there is just one thing that can rescue javaScript from this misery and that’s closure.&lt;/li&gt;
&lt;li&gt;inner goes to its parent scope and finds ‘b’ variable and remembers it, so when b was destroyed, it still remains in inner or x function and by calling x(), it will show us 80 (the result of a+b).
ok, just one more important example to be sure you got this:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fnl32xi5en2jp46p3s6vx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fnl32xi5en2jp46p3s6vx.png" alt=" " width="754" height="1192"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;1.we defined x = NumberFunc , so NumberFunc get invoked and i variable is declared with the value of 0 , incrementNumberFunc (closure) is saved inside x variable and now x is equel to incrementNumberFunc function and NumberFunc has been finished and i variable destroyed , but i value(10) remains inside the closure&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;the same thing is going with the ‘y’ variable&lt;/li&gt;
&lt;li&gt;&lt;p&gt;when we call x() for the first time it gets executed and the ‘b’ variable is declared with the value of 10, it logs the ‘i’ variable which is remained as 0 and ‘b’ as 10, and then increase their value by ++, so ‘i’ variable remains in closure with the new value of 1 and finally b variable is destroyed (note b variable does not remain in closure).&lt;br&gt;
&lt;code&gt;x(); //output : i = 0 , b = 10&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;second time is the same process but the ‘i’ value remained as 1(because we increased its value ++ in the previous execution ) and the ‘b’ variable is still 10 and not 11, it is because it was destroyed in the previous execution and not saved in closure.&lt;br&gt;
x(); //output : i = 1 , b = 10&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;the third time it is the same process as before&lt;br&gt;
x(); //output : i = 2 , b = 10&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;finally we call y() and when we declared y it saved i with value 0 so the output:&lt;br&gt;
y(); //output : i = 0 , b = 10&lt;br&gt;
if we call y() again, it will increase the ‘i’ variable to 1.&lt;br&gt;
so, we learned closure is the combination of function and ability to remember outer scope or parent function scope variables.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3.hoisting&lt;/strong&gt; **
&lt;/h2&gt;

&lt;p&gt;hoisting is a mechanism in javaScript that takes our declared variables, functions, classes to the top of their scope without their defined value and gives them undefined value as default.&lt;br&gt;
when we define a variable or function it has a lifecycle which is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Declaration:
&lt;code&gt;var i;&lt;/code&gt;
2.assignment/ initialisation:
&lt;code&gt;i = 20;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;usage:
&lt;code&gt;console.log(i + 22);&lt;/code&gt;
we usually do it in one line:
&lt;code&gt;var i = 20;&lt;/code&gt;
but it doesn’t matter how we do it, because javaScript declares it at the top and then assigns the value to it behind the scene before any code execution.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;note: if you assign a value to undeclared variable, javaScript will declares it itself in the global scope and assigns the value to it. ☺ :&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fzkqp2bc56g836dtt8k4o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fzkqp2bc56g836dtt8k4o.png" alt=" " width="800" height="464"&gt;&lt;/a&gt;&lt;br&gt;
so now that we know how javaScript handles variables, it is recommended to declare and assign a variable before using it.&lt;br&gt;
let me show you some examples that “what we see and what javaScript sees in our code “:&lt;br&gt;
&lt;strong&gt;Global scope:&lt;/strong&gt;&lt;br&gt;
what we see:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fm6q2o1r0zo8rejte0ixt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fm6q2o1r0zo8rejte0ixt.png" alt=" " width="754" height="596"&gt;&lt;/a&gt;&lt;br&gt;
what js sees:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F70i4e4ewav5iy6w29e3g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F70i4e4ewav5iy6w29e3g.png" alt=" " width="754" height="670"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Local scope:&lt;/strong&gt;&lt;br&gt;
what we see:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fnas5gils8muctv8gx08f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fnas5gils8muctv8gx08f.png" alt=" " width="754" height="670"&gt;&lt;/a&gt;&lt;br&gt;
what js sees:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fv8f2n3s8em743ocvkvfz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fv8f2n3s8em743ocvkvfz.png" alt=" " width="754" height="782"&gt;&lt;/a&gt;&lt;br&gt;
one of the other differences of let and const with the var keyword is :&lt;br&gt;
in the situations that we saw above, the ‘let’ and ‘const’ keyword gets mad and won’t let you use variables before initializing it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Frfqldzntwfz43od0vyvn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Frfqldzntwfz43od0vyvn.png" alt=" " width="754" height="632"&gt;&lt;/a&gt;&lt;br&gt;
of course, you should know, if you declare a variable with an undefined value and give it a value after usage will not cause an error :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Frpaeyjj79ou68nbay0oe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Frpaeyjj79ou68nbay0oe.png" alt=" " width="754" height="632"&gt;&lt;/a&gt;&lt;br&gt;
now let’s dive into other examples for functions and classes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Functions:&lt;/strong&gt;&lt;br&gt;
we have two types of functions in js :&lt;br&gt;
1.function declaration&lt;br&gt;
&lt;code&gt;function someFunc(){ //code }&lt;/code&gt;&lt;br&gt;
in this type of function, javaScript take it to the top of its scope with its declared value (that is why we can use functions before declaring them):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fsesppcc6fvba4p97odmo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fsesppcc6fvba4p97odmo.png" alt=" " width="750" height="558"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2.function expression&lt;br&gt;
&lt;code&gt;var someFunc = function (){//code}&lt;/code&gt;&lt;br&gt;
in this type, javaScript just take the declared name to the top with undefined value as default and not the given value and when we call the function before declaration it causes an error of “expression is not a function”, because it is not a function and it is an undefined:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Favobd9cxt4ikpmeoveqe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Favobd9cxt4ikpmeoveqe.png" alt=" " width="754" height="670"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;classes:&lt;/strong&gt;&lt;br&gt;
we have two types of classes in js:&lt;br&gt;
1.class declaration:&lt;br&gt;
&lt;code&gt;class SomeClass{&lt;br&gt;
constructor(name, lasname) {&lt;br&gt;
this.name= name; this.lastname= lastname;&lt;br&gt;
}&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
in this type of class, javaScript is not gonna hoist it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fd4r5b5g2ru0y9js8x2u0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fd4r5b5g2ru0y9js8x2u0.png" alt=" " width="754" height="930"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2.class expression:&lt;br&gt;
&lt;code&gt;var someClass = class{&lt;br&gt;
constructor(name, lasname) {&lt;br&gt;
this.name= name; this.lastname= lastname;&lt;br&gt;
}&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
in this type, javaScript takes it to the top with undefined value as default, so it causes an error when we use it before assignment:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fjbwb4a8kg5g2gq6rmr3j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fjbwb4a8kg5g2gq6rmr3j.png" alt=" " width="754" height="968"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;well, this article ends up here, I hope you learned something from it ☺&lt;br&gt;
Goodbye and Good luck🤞&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>hoisting</category>
      <category>scopes</category>
      <category>closure</category>
    </item>
  </channel>
</rss>
