<?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: Diana</title>
    <description>The latest articles on DEV Community by Diana (@dianalanciano).</description>
    <link>https://dev.to/dianalanciano</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%2F1948694%2Fcfecbf5d-482d-4e4a-8834-9a4380ad3cb2.jpg</url>
      <title>DEV Community: Diana</title>
      <link>https://dev.to/dianalanciano</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dianalanciano"/>
    <language>en</language>
    <item>
      <title>Async, Await in Javascript</title>
      <dc:creator>Diana</dc:creator>
      <pubDate>Thu, 24 Oct 2024 09:25:38 +0000</pubDate>
      <link>https://dev.to/dianalanciano/async-await-in-javascript-lk0</link>
      <guid>https://dev.to/dianalanciano/async-await-in-javascript-lk0</guid>
      <description>&lt;p&gt;In Javascript async, await provide more readable and "cleaner" way to  work with promises. (&lt;a href="https://dev.to/dianalanciano/promise-in-javascript-79p"&gt;You can read about promises here&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;First let's understand the syntax.&lt;/p&gt;

&lt;h2&gt;
  
  
  async Keyword:
&lt;/h2&gt;

&lt;p&gt;We have the &lt;code&gt;async&lt;/code&gt; key word, when we declaring that a function is &lt;code&gt;async&lt;/code&gt; we know that this function will always return a promise. Even if you return a value directly, JavaScript automatically wraps it in a promise.&lt;/p&gt;

&lt;h2&gt;
  
  
  await Keyword:
&lt;/h2&gt;

&lt;p&gt;First of all we must know that if we want to use the await keyword, we can only use it inside an async function.&lt;br&gt;
This &lt;code&gt;await&lt;/code&gt; keyword is pausing the execution of an async function until the promise is resolved or rejected.&lt;/p&gt;

&lt;p&gt;Let's see a very simple example of async/await and after that we will use a bigger example that will compare the full promises approach (without async/await) to the async/await approach.&lt;/p&gt;

&lt;h2&gt;
  
  
  simple example of async/await:
&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%2Fgpcljsdy4esyev9guq58.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%2Fgpcljsdy4esyev9guq58.png" alt="Image description" width="800" height="550"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's break it:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;response.ok&lt;/code&gt;: This property checks if the HTTP status code of the response is in the successful range (200-299).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;response.json()&lt;/code&gt;: If the response is successful, this function parses the JSON data returned by the server.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;response.status&lt;/code&gt;: This gives you the exact status code, such as 404 (Not Found) or 500 (Server Error).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that we understand the basics of async/await let's dive deeper and see another example with promises.&lt;br&gt;
We have 3 functions, each function is returning a promise:&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%2F7m0juaai6qstz51c3gpv.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%2F7m0juaai6qstz51c3gpv.png" alt="Image description" width="800" height="1079"&gt;&lt;/a&gt;&lt;br&gt;
(The explanation for those function you can find &lt;a href="https://dev.to/dianalanciano/promise-in-javascript-79p"&gt;here&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Now, we can call those function with &lt;code&gt;than()&lt;/code&gt; and &lt;code&gt;catch()&lt;/code&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%2Fmj2odnimlww3sgs0bk88.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%2Fmj2odnimlww3sgs0bk88.png" alt="Image description" width="800" height="687"&gt;&lt;/a&gt;&lt;br&gt;
This code is an example of promise chaining in JavaScript, where asynchronous operations (like fetching data) are performed sequentially, and each step relies on the result of the previous one.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Once &lt;code&gt;getOrders(user.id)&lt;/code&gt; resolves, it passes the orders array to the callback function inside the next &lt;code&gt;.then()&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The orders are logged to the console.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then, &lt;code&gt;getOrderDetails(orders[1]&lt;/code&gt;) is called, which takes the second order in the orders array (assuming it exists).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This function returns a &lt;strong&gt;promise&lt;/strong&gt; that resolves when the order details are fetched.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The promise from &lt;code&gt;getOrderDetails()&lt;/code&gt; is returned, so the next &lt;code&gt;.then()&lt;/code&gt; waits for this promise to resolve.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;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%2Flvd0eyieh0zua6kdgszq.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%2Flvd0eyieh0zua6kdgszq.png" alt="Image description" width="405" height="159"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Async/Await approach:
&lt;/h2&gt;

&lt;p&gt;This code is an example of how async/await is used in JavaScript to handle asynchronous operations in a more readable, compared to the promise chaining 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%2F6091rwvmxlujxkyr4ut9.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%2F6091rwvmxlujxkyr4ut9.png" alt="Image description" width="800" height="486"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;:&lt;br&gt;
1.&lt;code&gt;async function asyncAwaitExample():&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This function is marked as &lt;code&gt;async&lt;/code&gt;, which means it will always 
return a promise. It allows the use of the await keyword within it.

&lt;ul&gt;
&lt;li&gt;Inside the function, asynchronous code can be written in a way that looks and behaves like synchronous code, improving readability.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;try { ... } catch (error) { ... }:&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;try-catch&lt;/code&gt; block is used to handle errors. Any errors that occur during the execution of asynchronous operations will be caught in the catch block.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;const user = await getUser(1);&lt;/code&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;await&lt;/code&gt; keyword pauses the execution of the function until the &lt;code&gt;getUser(1&lt;/code&gt;) promise is resolved.
-Once the &lt;code&gt;getUser&lt;/code&gt; promise resolves, the result (the user object) is stored in the &lt;code&gt;user&lt;/code&gt; variable
-If the promise is rejected (i.e., an error occurs), it jumps to the catch block to handle the error
-Same operation for &lt;code&gt;const Order&lt;/code&gt;, &lt;code&gt;const details&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4.&lt;code&gt;catch (error) { console.log("error is:", error); }:&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If any of the asynchronous functions (&lt;code&gt;getUser&lt;/code&gt;, &lt;code&gt;getOrders&lt;/code&gt;, or &lt;code&gt;getOrderDetails&lt;/code&gt;) throw an error or their promise is rejected, execution jumps to the catch block.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;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%2Ftn1f4dzacshrfyhho5bg.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%2Ftn1f4dzacshrfyhho5bg.png" alt="Image description" width="449" height="159"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of async/await:
&lt;/h2&gt;

&lt;p&gt;1.&lt;strong&gt;Readability&lt;/strong&gt;: Asynchronous code looks like synchronous code, reducing the need for nesting .then() blocks or dealing with callback hell.&lt;br&gt;
2.&lt;strong&gt;Error Handling&lt;/strong&gt;: With a simple try-catch block, you can handle errors in a more straightforward manner than using .catch() with promises.&lt;br&gt;
3.&lt;strong&gt;Maintainability&lt;/strong&gt;: As the logic becomes more complex, it’s easier to follow and maintain with async/await than with promise chains.&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%2F67g9qmn9hd4o5v642kbm.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%2F67g9qmn9hd4o5v642kbm.png" alt="Image description" width="515" height="325"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Promise in Javascript</title>
      <dc:creator>Diana</dc:creator>
      <pubDate>Sun, 20 Oct 2024 06:04:05 +0000</pubDate>
      <link>https://dev.to/dianalanciano/promise-in-javascript-79p</link>
      <guid>https://dev.to/dianalanciano/promise-in-javascript-79p</guid>
      <description>&lt;h2&gt;
  
  
  Promise
&lt;/h2&gt;

&lt;p&gt;represents a value that may be available now, or in the future, or never. &lt;br&gt;
Promise Life Cycle:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Pending: The function starts to work.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Fulfilled: The operation completed successfully, and we have a result value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Rejected: The operation failed, and we have an error object.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Syntax of a Promise:&lt;/p&gt;

&lt;p&gt;A promise is created using the new Promise constructor, which takes a function with two arguments: resolve and reject.&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%2Fun2fkajzp223q6fgjbk8.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%2Fun2fkajzp223q6fgjbk8.png" alt="Image description" width="800" height="412"&gt;&lt;/a&gt;&lt;br&gt;
In the code snippet, we have a function called &lt;code&gt;getUser&lt;/code&gt;, which returns a &lt;code&gt;new Promise&lt;/code&gt; (a promise object that has methods to handle asynchronous operations).&lt;/p&gt;

&lt;p&gt;Inside the Promise constructor, we have a setTimeout function that simulates an asynchronous operation, such as fetching data from a database. The promise has two key methods passed to it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;resolve: This is called when the operation is successful. In this case, if &lt;code&gt;id === 1&lt;/code&gt;, it returns a mock user object &lt;code&gt;{ id: 1, name: "Diana", email: "Diana@test.com" }&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;reject: This is called when the operation fails. If the id is not 1, the promise is rejected with an error message "User not found...".&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The resolve and reject functions act like return statements in the context of promises, allowing the caller to handle the success or failure of the operation.&lt;/p&gt;
&lt;h2&gt;
  
  
  Chaining Promises
&lt;/h2&gt;

&lt;p&gt;Promises can be chained, allowing you to perform a series of asynchronous operations in sequence:&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%2Fc12ydgyp6qemyxz28z8k.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%2Fc12ydgyp6qemyxz28z8k.png" alt="Image description" width="800" height="1492"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we are chaining multiple promises to simulate fetching data step by step.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;First, we call &lt;code&gt;getUser(1)&lt;/code&gt; to get the user data. If it works, we move to the next step.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Second, we take the &lt;code&gt;user.id&lt;/code&gt; and use it to get the orders for that user by calling &lt;code&gt;getOrders(user.id)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;-Third, we pick the second order &lt;code&gt;(orders[1])&lt;/code&gt; from the list and get its details using &lt;code&gt;getOrderDetails(orders[1])&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If anything goes wrong at any point (like the user not being found or orders missing), the error will be caught in the &lt;code&gt;.catch()&lt;/code&gt; block and displayed.&lt;/p&gt;
&lt;h2&gt;
  
  
  Simple Breakdown:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;You ask for a user.&lt;/li&gt;
&lt;li&gt;If you find the user, you ask for their orders.&lt;/li&gt;
&lt;li&gt;If you get the orders, you ask for details about one of the orders.&lt;/li&gt;
&lt;li&gt;If anything goes wrong (like the user or orders not being found), - it will show an error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;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%2Ff9mb18adk7dyaw5x444y.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%2Ff9mb18adk7dyaw5x444y.gif" alt="Image description" width="480" height="296"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This approach makes it easier to work with asynchronous tasks in a clean, step-by-step way instead of having messy code.&lt;/p&gt;
&lt;h2&gt;
  
  
  Promise Methods:
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Promise.all()&lt;/code&gt;: Executes multiple promises in parallel and waits until all of them are resolved.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Promise.all([promise1, promise2])
  .then((results) =&amp;gt; {
    console.log(results);  // Array of all fulfilled values
  });

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

&lt;/div&gt;



&lt;p&gt;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%2Fq0lbgn8oeo4le2ntiloq.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%2Fq0lbgn8oeo4le2ntiloq.png" alt="Image description" width="800" height="243"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;(I recommend to read and compare this approach to &lt;a href="https://dev.to/dianalanciano/promises-callbacks-async-await-1iln"&gt;callbacks&lt;/a&gt;)&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Callbacks in Javascript</title>
      <dc:creator>Diana</dc:creator>
      <pubDate>Sat, 19 Oct 2024 14:24:56 +0000</pubDate>
      <link>https://dev.to/dianalanciano/promises-callbacks-async-await-1iln</link>
      <guid>https://dev.to/dianalanciano/promises-callbacks-async-await-1iln</guid>
      <description>&lt;p&gt;In JavaScript we have different ways to handle asynchronous calls.&lt;br&gt;
It allows you to handle asynchronous tasks like fetching data from a server, reading files, or waiting for an event.&lt;/p&gt;
&lt;h2&gt;
  
  
  Callbacks
&lt;/h2&gt;

&lt;p&gt;This is a function that calls to another function.&lt;br&gt;
Let's see an example so we can understand it better:&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%2Fr3d22tyd6mlkss0zt1fx.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%2Fr3d22tyd6mlkss0zt1fx.png" alt="Image description" width="800" height="430"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Calling &lt;code&gt;getUser()&lt;/code&gt; with an id and callback function that will print users id, name and email. The callback will be executed once the asynchronous &lt;code&gt;getUser&lt;/code&gt; operation completes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;getUser()&lt;/code&gt; Function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;id: This is the id of the user you want to retrieve passed from the getUser(1, ...) call.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;callback: This is the function that will be called after the "user data" is retrieved (simulated here by the &lt;code&gt;setTimeout()&lt;/code&gt; function).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside the &lt;code&gt;setTimeout()&lt;/code&gt; function the &lt;code&gt;callback()&lt;/code&gt; function is called after the delay, passing a mock user object as its argument: &lt;code&gt;{ id: id, name: 'Diana', email: 'Diana@test.com' }&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Execution Flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;getUser(1, user =&amp;gt; { console.log('User', user); });&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;Inside &lt;code&gt;getUser()&lt;/code&gt;, a 3-second delay is triggered using &lt;code&gt;setTimeout()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;After 3 seconds: The message 'Fetching user from DB...' is logged to the console. The callback function is invoked with the user object &lt;code&gt;{ id: 1, name: 'Diana', email: 'Diana@test.com' }&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The callback function logs &lt;code&gt;User&lt;/code&gt; and the user object to the console.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Final Output:&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%2Ffelfa5fewi08cnby00cc.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%2Ffelfa5fewi08cnby00cc.png" alt="Image description" width="708" height="85"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Callback Hell
&lt;/h2&gt;

&lt;p&gt;Callback hell pattern - this happens when multiple asynchronous operations depend on each other, leading to deeply nested callbacks. As the nesting increases, the code becomes harder to read, maintain, and debug. 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%2Frdh4o8i0zq7cwevdl410.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%2Frdh4o8i0zq7cwevdl410.png" alt="Image description" width="800" height="648"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's break it down:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Fetching the User:&lt;/strong&gt;
Here, we initiate the first asynchronous call, &lt;code&gt;getUser(1)&lt;/code&gt;, which simulates fetching user data from a database. Once the data is fetched, the callback function is executed, logging the user details to the console.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getUser(1, user =&amp;gt; {
    console.log('User', user);
    // ...
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Fetching the User's Orders:&lt;/strong&gt;&lt;br&gt;
Inside the callback for &lt;code&gt;getUser()&lt;/code&gt;, we make another asynchronous call to &lt;code&gt;getOrders(user.id)&lt;/code&gt;, simulating fetching the user's orders from the database. This requires nesting another callback inside the first one. Once the orders are fetched, the orders are logged.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getOrders(user.id, orders =&amp;gt; {
    console.log(`${user.name}'s orders`, orders);
    // ...
});

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Fetching the Order Details:&lt;/strong&gt;
After fetching the orders, we need to get the details of one specific order &lt;code&gt;(orders[1])&lt;/code&gt;. This leads to a third level of nesting, where &lt;code&gt;getOrdersDetails()&lt;/code&gt; is called to fetch the order details, and then logs them to the console.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getOrdersDetails(orders[1], details =&amp;gt; {
    console.log('Order Details', details);
});

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

&lt;/div&gt;



&lt;p&gt;Code Structure (Nesting):&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%2Fufvxx9fxec3gieoq8s5z.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%2Fufvxx9fxec3gieoq8s5z.png" alt="Image description" width="800" height="339"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice how each asynchronous operation depends on the previous one, resulting in a deeply nested structure. Making the code difficult to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Read&lt;/strong&gt;: It’s hard to follow the flow of the logic when callbacks are deeply nested.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error handling:&lt;/strong&gt; It's difficult to handle errors at multiple levels of callbacks.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;3.&lt;strong&gt;Debug:&lt;/strong&gt; Identifying where an error occurs becomes more complex when many levels of callbacks are involved.&lt;/p&gt;

&lt;p&gt;Also it makes the code "Tight coupling" - each function depends on the previous one’s output, which means that the code is tightly coupled, reducing reusability.&lt;/p&gt;

&lt;p&gt;Result:&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%2Fm466g9ijvvr8qp1aghs9.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%2Fm466g9ijvvr8qp1aghs9.gif" alt="Image description" width="480" height="356"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Avoiding Callback Hell:&lt;br&gt;
Callback hell can be avoided by using modern JavaScript features like Promises and async/await. These methods allow asynchronous code to be written in a more readable, sequential manner.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>learning</category>
    </item>
    <item>
      <title>Synchronous and asynchronous code in javascript</title>
      <dc:creator>Diana</dc:creator>
      <pubDate>Thu, 19 Sep 2024 07:48:47 +0000</pubDate>
      <link>https://dev.to/dianalanciano/synchronous-and-asynchronous-code-in-javascript-44jk</link>
      <guid>https://dev.to/dianalanciano/synchronous-and-asynchronous-code-in-javascript-44jk</guid>
      <description>&lt;p&gt;In JavaScript, synchronous and asynchronous code refer to the way tasks are executed and handled. Before we are diving into Callbacks, Promises, Async Await let's understand the difference between these two concepts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Synchronous code:
&lt;/h2&gt;

&lt;p&gt;Basically it's a code that executed line by line. Each line waits to the previous one to complete. This means that the code is executed in the order that is written.&lt;/p&gt;

&lt;p&gt;Example of Synchronous Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Start'); // This will run first
console.log('Hello World'); // This will run second
console.log('Finish'); // This will run third
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, if a task takes time, such as a long loop or a blocking operation (like file I/O or database access), it can cause delays in the entire application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Start');
for (let i = 0; i &amp;lt; 1000000000; i++) {
  // Simulating a long-running task
}
console.log('End');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The loop takes several seconds, the program will be "frozen" until it completes, making it unresponsive to user interactions or other events.&lt;/p&gt;

&lt;h2&gt;
  
  
  Asynchronous Code:
&lt;/h2&gt;

&lt;p&gt;Asynchronous code allows JavaScript to start a task but not wait for it to complete before moving on to the next one. JavaScript can continue executing other tasks and come back to the asynchronous task once it's done.&lt;/p&gt;

&lt;p&gt;Non-blocking - JavaScript has a single-threaded execution model, meaning it can only execute one task at a time. However, the event loop enables it to handle asynchronous tasks without blocking the main thread. It does this by delegating time-consuming operations (like network requests, file I/O, timers, etc.) to external APIs (e.g., Web APIs in the browser) or the environment (Node.js APIs). Once these tasks are completed, the event loop adds the results (callbacks or promises) back to the task queue or microtask queue for execution when the main call stack is clear.&lt;/p&gt;

&lt;p&gt;Callbacks, Promises, and Async/Await are tools or mechanisms that enable us to work with asynchronous tasks more easily within this event loop model. They don't make JavaScript non-blocking on their own but help you manage the non-blocking behavior effectively.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Task 1'); // This will run first

setTimeout(() =&amp;gt; {
  console.log('Task 2'); // This will run after 3 second
}, 3000);

console.log('Task 3'); // This will run immediately after Task 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Asynchronous code makes it possible to handle tasks like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fetching data from a server.&lt;/li&gt;
&lt;li&gt;Waiting for a user input.&lt;/li&gt;
&lt;li&gt;Timers, like setTimeout or setInterval.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How the Event Loop works:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Call stack- Manages the execution of all functions in a single-threaded manner, using a stack to track function calls.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Web APIs- A set of functionality to interact with the browser features. When an asynchronous operation (like setTimeout or fetch) is invoked, it's handed over to the Web API. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Task queue/callback queue- Holds Web API callbacks, once the asynchronous operation completes, the associated callback is placed in the callback queue. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Event loop- Responsible to check if the call stack is empty. If the queue is empty it takes a task from the microtask queue, if the microtask is empty he taking tasks from callback queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Microtask queue- When we working with promises we are using the microtask queue. The event loop priorities the microtask queue. This is a special queue dedicated to the next callback:&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.then(() =&amp;gt; {...})&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.catch(() =&amp;gt; {...})&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.finally(() =&amp;gt; {...})&lt;/code&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Function body after await&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;queueMicrotask(): This function explicitly adds a task to the microtask queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MutationObserver: This is another example of a mechanism that adds tasks to the microtask queue. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Async example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Start');

setTimeout(() =&amp;gt; {
  console.log('Async Task Complete');
}, 1000); // Asynchronous operation, handled by Web API

console.log('End');

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

&lt;/div&gt;



&lt;p&gt;Execution flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;console.log('Start')&lt;/code&gt; runs first, logging "Start".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;setTimeout()&lt;/code&gt; Registering to Web APIs, the asynchronous task is scheduled to move into the callback queue after 1 second and will log 'Async Task Complete' when the call stack is empty (note that it may take longer than 1 second if the call stack is not empty).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;console.log('End') runs immediately, logging "End".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After 1 second, the event loop pulls the callback from the callback queue and logs "Async Task Complete".&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>softwaredevelopment</category>
      <category>beginners</category>
    </item>
    <item>
      <title>The React Hooks Explained</title>
      <dc:creator>Diana</dc:creator>
      <pubDate>Sun, 15 Sep 2024 06:27:41 +0000</pubDate>
      <link>https://dev.to/dianalanciano/the-react-hooks-explained-1mlh</link>
      <guid>https://dev.to/dianalanciano/the-react-hooks-explained-1mlh</guid>
      <description>&lt;p&gt;React Hooks have simplified the way we write React components. With Hooks, we can manage state, handle side effects, and more, all within functional components. Introduced in React 16.8, Hooks allow us to use state and other React features in functional components, making our code simpler and more intuitive. &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%2Fyi5y071bilz8vsy6h5th.jpg" 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%2Fyi5y071bilz8vsy6h5th.jpg" alt="Image description" width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  useState hook:
&lt;/h2&gt;

&lt;p&gt;The most common hook is the useState hook. To understand useState, let's first try to understand what state is.&lt;/p&gt;

&lt;p&gt;State refers to data that will change and needs to be tracked. So, let's see the structure of the &lt;code&gt;useState&lt;/code&gt; 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%2Fqgurczny3dbj9iluvahb.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%2Fqgurczny3dbj9iluvahb.png" alt="Image description" width="800" height="803"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;n this example, we have two states: &lt;code&gt;name&lt;/code&gt; on line 4 and &lt;code&gt;displayName&lt;/code&gt; on line 5. &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;displayName&lt;/code&gt; are the state variables that we are trying to track. &lt;code&gt;setName&lt;/code&gt; and &lt;code&gt;setDisplayName&lt;/code&gt; are the update functions that will be triggered when we want to update the value of the state variables.&lt;/p&gt;

&lt;p&gt;We start with an empty string for each state variable (as we see in the parentheses of each state on lines 4 and 5—the starting value is optional, but note that you will have an empty state if you do not provide a default value).&lt;/p&gt;

&lt;p&gt;By convention, the update function name will always have a prefix of set followed by the state variable name.&lt;/p&gt;

&lt;p&gt;The state &lt;code&gt;name&lt;/code&gt; is tracking what the user is typing in the input on line 17. Every time the value in the input changes, &lt;code&gt;handleInputChange&lt;/code&gt; is triggered, and inside this function, we set name with the current value using &lt;code&gt;setName&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Similarly, we have &lt;code&gt;displayName&lt;/code&gt;, which is the name that will be displayed when the user clicks the button we created on line 18.&lt;/p&gt;

&lt;p&gt;Every time we change the input, the &lt;code&gt;name&lt;/code&gt; state is updated (I added a log so we can see it):&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%2Fa29drb5cpkc1mv3m53ww.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%2Fa29drb5cpkc1mv3m53ww.gif" alt="Image description" width="480" height="386"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Only when we click on the button the &lt;code&gt;displayName&lt;/code&gt; will be set to the current value we have in the &lt;code&gt;name&lt;/code&gt; state. (what we see in the console is the &lt;code&gt;name&lt;/code&gt; state changing)&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%2Flg2y7cajbn5d50ajn6ce.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%2Flg2y7cajbn5d50ajn6ce.gif" alt="Image description" width="304" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  useEffect hook:
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;useEffect&lt;/code&gt; hook allows us to perform side effects in our application. In simple terms, side effects are things that happen as a result of some task we performed, like data fetching, updating the DOM, and more.&lt;/p&gt;

&lt;p&gt;Let's understand the structure of the &lt;code&gt;useEffect&lt;/code&gt; 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%2Fb2qinx3pxckttxiyzeeu.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%2Fb2qinx3pxckttxiyzeeu.png" alt="Image description" width="800" height="345"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPORTANT&lt;/strong&gt;: It's guaranteed that the &lt;code&gt;useEffect&lt;/code&gt; will run at least once. If no dependency is given in the dependency array, the &lt;code&gt;useEffect&lt;/code&gt; will run only one time when the component mounts.&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%2Ffphpljvlwdiai978b2oc.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%2Ffphpljvlwdiai978b2oc.png" alt="Image description" width="800" height="943"&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%2Fsspfqyy0ayg3dk7jhqpm.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%2Fsspfqyy0ayg3dk7jhqpm.gif" alt="Image description" width="274" height="480"&gt;&lt;/a&gt;&lt;br&gt;
In this example, the effect is a &lt;code&gt;console.log&lt;/code&gt; of the state variable count. Every time &lt;code&gt;count&lt;/code&gt; changes, the &lt;code&gt;useEffect&lt;/code&gt; is triggered because we're listening to count in our dependency array.&lt;/p&gt;

&lt;p&gt;Now, let's understand how the cleanup function works. To do this, we need to understand the lifecycle of the &lt;code&gt;useEffect&lt;/code&gt; hook. Let's add another console.log for the cleanup function:&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%2Fmfzsjkqoi7e0upy0qzhp.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%2Fmfzsjkqoi7e0upy0qzhp.png" alt="Image description" width="800" height="896"&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%2Fxesm7bf77ski4xsc3gey.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%2Fxesm7bf77ski4xsc3gey.gif" alt="Image description" width="260" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, when we run our code and change the &lt;code&gt;count&lt;/code&gt;, the component is re-rendered then the cleanup function is running and then the code in the useEffect.&lt;/p&gt;

&lt;h2&gt;
  
  
  useRef hook:
&lt;/h2&gt;

&lt;p&gt;The useRef hook is used to track or store values without triggering a re-render. The value from &lt;code&gt;useRef&lt;/code&gt; will not be used in the return body. It takes an initial value and returns an object with a current property. Let’s look at an example of useRef to understand how it works. We’ll also compare it to the useState hook for better understanding.&lt;/p&gt;

&lt;p&gt;We have here the example of the counter with the useRef hook:&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%2F5p512s6z5qv64bhjq4jm.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%2F5p512s6z5qv64bhjq4jm.png" alt="Image description" width="800" height="794"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When we increment the number, we will still see 0. This is because it's not causing a re-render, but in the console, we can see that the value is updated correctly:&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%2Fms7c2kzzl08croskmslx.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%2Fms7c2kzzl08croskmslx.gif" alt="Image description" width="262" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So now we know: &lt;code&gt;useRef&lt;/code&gt; is a hook that provides a way to persist values across renders without causing a re-render when those values change. This makes it ideal for scenarios where you want to store information that doesn't need to affect the rendering process, such as keeping track of previous values or interacting with DOM elements directly.&lt;br&gt;
Additionally, &lt;code&gt;useRef&lt;/code&gt; can be used to access DOM elements, making it useful for controlling focus, text selection, or animations in functional components. Since it persists through renders and doesn't cause re-renders, &lt;code&gt;useRef&lt;/code&gt; is efficient for certain tasks where you don't need to update the UI.&lt;/p&gt;

&lt;h2&gt;
  
  
  useMemo hook:
&lt;/h2&gt;

&lt;p&gt;The useMemo hook is commonly used to optimize performance by memoizing the result of a computation. It acts like a cache between re-renders, ensuring that expensive calculations are only re-executed when one of the dependencies changes. This helps avoid unnecessary recalculations on every re-render, making your component more efficient.&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%2F28k6dprpzlpr7y0owuuv.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%2F28k6dprpzlpr7y0owuuv.png" alt="Image description" width="800" height="1085"&gt;&lt;/a&gt;&lt;br&gt;
doubleNumber Function:&lt;/p&gt;

&lt;p&gt;This function simulates an expensive operation with a loop &lt;code&gt;(for(let i = 0; i&amp;lt;= 10000000000; i++) {})&lt;/code&gt; and doubles the input number. It's a heavy computation meant to illustrate performance optimization.&lt;br&gt;
Every time the component re-renders, running this function would normally cause a performance delay.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useMemo(() =&amp;gt; doubleNumber(count), [count])&lt;/code&gt;: The useMemo hook memoizes (caches) the result of &lt;code&gt;doubleNumber(count)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It only re-executes doubleNumber when the count state changes. This means if the component re-renders due to changes in the color state, the expensive &lt;code&gt;doubleNumber&lt;/code&gt; function won't run again unless count has changed.&lt;/p&gt;

&lt;p&gt;We can see that when we press on &lt;code&gt;Increment&lt;/code&gt; the operation takes time, but the change color is immediate:&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%2F238vfkwroe144tdyzaqf.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%2F238vfkwroe144tdyzaqf.gif" alt="Image description" width="480" height="306"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  useCallback hook:
&lt;/h2&gt;

&lt;p&gt;This hook is very similar to the &lt;code&gt;useMemo&lt;/code&gt; hook. The difference between them is that &lt;code&gt;useMemo&lt;/code&gt; takes a function and returns the result of that function, while &lt;code&gt;useCallback&lt;/code&gt; takes a function and returns the function itself. &lt;/p&gt;

&lt;p&gt;In the next example, we can see that when the component re-renders, the &lt;code&gt;getNumbers&lt;/code&gt; function is recreated, even if only the color has changed. Therefore, each time the component updates, it generates a new function, even though the actual number did not change:&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%2Fgqong4f2wj79xx9105cq.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%2Fgqong4f2wj79xx9105cq.png" alt="Image description" width="800" height="1111"&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%2F62mugufwecysiuupswz4.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%2F62mugufwecysiuupswz4.png" alt="Image description" width="800" height="492"&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%2Feaff1s3yvb8tdb7pra43.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%2Feaff1s3yvb8tdb7pra43.gif" alt="Image description" width="456" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can fix it with &lt;code&gt;useCallback&lt;/code&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%2F2sk6zfvmpoixuzlioolr.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%2F2sk6zfvmpoixuzlioolr.png" alt="Image description" width="800" height="349"&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%2Fvuved5ykzg8u8nsd7dvo.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%2Fvuved5ykzg8u8nsd7dvo.gif" alt="Image description" width="308" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  useContext hook:
&lt;/h2&gt;

&lt;p&gt;The useContext hook in React is used to access values from a context without needing to pass props down through multiple layers of the component tree. It simplifies prop drilling by allowing components to subscribe to context values directly.&lt;/p&gt;

&lt;p&gt;What is a Context?&lt;br&gt;
Context is a way to share data (like a global variable) between components without having to pass it explicitly via props at every level. This is useful for things like themes, user authentication, or settings, where multiple components need access to the same data.&lt;/p&gt;

&lt;p&gt;How useContext Works:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Creating a Context:&lt;br&gt;
First, you create a context using &lt;code&gt;React.createContext()&lt;/code&gt;. This creates a "context object" which holds the value you want to share.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Providing the Context Value:&lt;br&gt;
Next, you wrap the components that need access to the context with the &lt;code&gt;Context.Provider component&lt;/code&gt;. The Provider accepts a value prop, which is the data that will be available to all the components that use this context.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consuming the Context Value:&lt;br&gt;
Inside a child component, instead of passing props down, you can use the &lt;code&gt;useContext&lt;/code&gt; hook to access the value of the context.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the next example, we create a context in the Example component (line 5). Then, we wrap the User component with  so that any children within the User component tree can access the context. Finally, the PersonalInfo and LocationInfo components consume the context and display the data using const user = useContext(UserContext).&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%2Fiihnvszg34ibtvaj9cou.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%2Fiihnvszg34ibtvaj9cou.png" alt="Image description" width="800" height="891"&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%2F4uzddoi5kajbhkkqp003.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%2F4uzddoi5kajbhkkqp003.png" alt="Image description" width="800" height="705"&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%2F1crzlvgmxa9iyqv0g1l2.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%2F1crzlvgmxa9iyqv0g1l2.png" alt="Image description" width="800" height="614"&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%2Fbssp2fh8i0mr1bpb928i.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%2Fbssp2fh8i0mr1bpb928i.png" alt="Image description" width="800" height="606"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;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%2Faiynpve9f9lvphrf142v.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%2Faiynpve9f9lvphrf142v.png" alt="Image description" width="620" height="317"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  useReducer hook:
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;useReducer&lt;/code&gt; hook in React is a more advanced alternative to useState. It helps manage complex state logic in components, especially when the state depends on multiple actions or is composed of multiple values.&lt;br&gt;
When you have complex state logic that involves multiple sub-values or state transitions or the next state depends on the previous state, you probably will need the &lt;code&gt;useReducer&lt;/code&gt;.&lt;br&gt;
Let's check the example and understand from it how it works:&lt;br&gt;
In line 15 we declaring on the useReducer hook it takes 2 parameters that are mandatory:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;reducer&lt;/code&gt;: A function that determines how the state should change, based on the action dispatched. We created the function in line 3-12.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;{ count : 0 }&lt;/code&gt;: The starting state of your component. Usually, we use an object because we have complex variables.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;dispatch&lt;/code&gt;: A function you call with an action to trigger the reducer function. We have the &lt;code&gt;dispatch&lt;/code&gt; in the &lt;code&gt;increment&lt;/code&gt; and &lt;code&gt;decrement&lt;/code&gt; functions.&lt;/p&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%2Fxn5m1ybd3olxb8ao9f2h.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%2Fxn5m1ybd3olxb8ao9f2h.png" alt="Image description" width="800" height="1036"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the reducer function, we always check the action type to determine the appropriate action. I used a switch statement, but you can also use if statements (although switch tends to be more readable).&lt;br&gt;
Each time we click one of the buttons, the corresponding button's function is triggered, which calls the reducer function.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
