<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vidya Jayagouda on Medium]]></title>
        <description><![CDATA[Stories by Vidya Jayagouda on Medium]]></description>
        <link>https://medium.com/@vidya.jayagouda?source=rss-cf400c2f1da3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WEsTg3K9IA4jYruL</url>
            <title>Stories by Vidya Jayagouda on Medium</title>
            <link>https://medium.com/@vidya.jayagouda?source=rss-cf400c2f1da3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:52:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vidya.jayagouda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React Hooks — useMemo Hook In ReactJS]]></title>
            <link>https://blog.nonstopio.com/react-hooks-usememo-hook-in-reactjs-584db92783d5?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/584db92783d5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook-usememo]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 05:35:37 GMT</pubDate>
            <atom:updated>2024-02-06T05:58:50.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Hooks — useMemo Hook In ReactJS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL9wWOnX0fcOtWI6YLc4vQ.png" /></figure><h3>Introduction</h3><p>In my previous <a href="https://medium.com/nonstopio/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-ii-cf4fd5298a2a">blog</a>, I explained some of the React Hooks if you didn’t check please read it to understand in depth of each React Hook, In this blog will continue exploring React Hook which is <strong>useMemo()</strong></p><ol><li><strong>useMemo()</strong></li></ol><p>useMemo is a React Hook that lets you cache the result of a calculation between re-renders.<br>Memoization is the optimized technique used primarily to speed up computer programs by storing up results of the expensive function calls and returning cache results when the same input occurs.<br>The useMemo hook serves a similar purpose like useCallback , useMemo returns a memoized value instead of a function reference. This allows you to avoid repeatedly performing potentially costly operations until necessary. The useMemo Hook typically returns a cached value until a dependency gets changed. If a dependency gets changed, React will re-do the expensive calculation and update the memoized value.</p><p>Look at the following code that does a costly calculation with one state field:</p><pre>import { useState } from &#39;react&#39;;<br>function slowFunction(number) {<br> for (let i; i &lt; 11111111111111; i++) {}<br> return number * 3;<br>}<br>const Example = () =&gt; {<br> const [dark, setDark] = useState(false);<br> const [number, setNumber] = useState(0);<br><br> const trifleNumber = slowFunction(number);<br><br> const themes = {<br>  backgroundColor: dark ? &#39;black&#39; : &#39;white&#39;,<br>  color: dark ? &#39;white&#39; : &#39;black&#39;,<br>  marginBottom: &#39;10px&#39;,<br> };<br> const handleChangeThem = () =&gt; {<br>  setDark((prevDark) =&gt; !prevDark);<br> };<br> return (<br>  &lt;&gt;<br>   &lt;h1&gt;Welcome to React Hook UseMemo&lt;/h1&gt;<br>   &lt;div&gt;<br>    &lt;input<br>     value={number}<br>     type=&#39;number&#39;<br>     placeholder=&#39;Enter a number&#39;<br>     onChange={(e) =&gt; {<br>      setNumber(e.target.value);<br>     }}<br>    /&gt;<br>   &lt;/div&gt;<br>   &lt;div&gt;<br>    &lt;button onClick={handleChangeThem}&gt;Change the theme&lt;/button&gt;<br>   &lt;/div&gt;<br>   &lt;div style={themes}&gt;{trifleNumber}&lt;/div&gt;<br>  &lt;/&gt;<br> );<br>};<br>export default Example;</pre><p>The above code implements two main functional segments in the app:</p><ul><li>Change in the input number and triple number</li><li>Change the theme to dark or white</li></ul><p>Once you run the app, it will work as expected. whenever the number changes, slowFunction that takes a number parameter. which simulates a slow computation. It multiplies the number parameter by 3 and returns the result. when you click on the change theme button slowFunction<br>also get triggered.<br>There is a hidden issue. when you click on the Change Theme button, the app works slowly because the slowFunction triggered which is a costly operation.</p><p>The reason is that when a change in the number slowFunction also triggers so there will be a delay in printing the triple number, As a solution, we can wrap the slowFunctionfunction call with useMemo to let React use a cache value when the Example component re-renders when there is no change in the number</p><pre>const trifleNumber = useMemo(()=&gt;slowFunction(number), []); </pre><p>Now, the useMemo Hook calculates a trifle Number number only if the number dependency gets changed, so the Change Theme will work faster! You can check out the optimized example here:</p><pre>import { useMemo, useState } from &#39;react&#39;;<br>function slowFunction(number) {<br> for (let i; i &lt; 11111111111111; i++) {}<br> return number * 3;<br>}<br>const Example = () =&gt; {<br> const [dark, setDark] = useState(false);<br> const [number, setNumber] = useState(0);<br><br> // with useMemo<br> const trifleNumber = useMemo(() =&gt; {<br>  return slowFunction(number);<br> }, [number]);<br><br> const themes = {<br>  backgroundColor: dark ? &#39;black&#39; : &#39;white&#39;,<br>  color: dark ? &#39;white&#39; : &#39;black&#39;,<br>  marginBottom: &#39;10px&#39;,<br> };<br> const handleChangeThem = () =&gt; {<br>  setDark((prevDark) =&gt; !prevDark);<br> };<br> return (<br>  &lt;&gt;<br>   &lt;h1&gt;Welcome to React Hook UseMemo&lt;/h1&gt;<br>   &lt;div&gt;<br>    &lt;input<br>     value={number}<br>     type=&#39;number&#39;<br>     placeholder=&#39;Enter a number&#39;<br>     onChange={(e) =&gt; {<br>      setNumber(e.target.value);<br>     }}<br>    /&gt;<br>   &lt;/div&gt;<br>   &lt;div&gt;<br>    &lt;button onClick={handleChangeThem}&gt;Change the theme&lt;/button&gt;<br>   &lt;/div&gt;<br>   &lt;div style={themes}&gt;{trifleNumber}&lt;/div&gt;<br>  &lt;/&gt;<br> );<br>};<br>export default Example;</pre><h3>Conclusion</h3><p>The useMemo function is an instrument for fine-tuning React. Knowing how and when to use each could potentially improve application performance. Still, no inbuilt performance-improvement Hook is a substitute for a poorly written React app codebase. In this blog, we have provided a guide for understanding how to use these tools, but keep in mind that using them comes with a cost (memory usage for caching).</p><blockquote>Here to make the community stronger by sharing our knowledge. <a href="https://medium.com/@vidya.jayagouda">Follow me</a> and <a href="https://medium.com/nonstopio">my team</a> to stay updated on the latest and greatest in the web &amp; mobile tech world.</blockquote><h3>References</h3><p><a href="https://react.dev/reference/react/useReducer">React Document</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584db92783d5" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/react-hooks-usememo-hook-in-reactjs-584db92783d5">React Hooks — useMemo Hook In ReactJS</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Hooks: A Comprehensive Guide to Streamlining Your Component Magic[Part-II]]]></title>
            <link>https://blog.nonstopio.com/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-ii-cf4fd5298a2a?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf4fd5298a2a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 09:32:01 GMT</pubDate>
            <atom:updated>2024-01-31T09:37:06.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwahPBaloup2qnIdQoKsJw.png" /></figure><h4>Introduction</h4><p>In my previous <a href="https://medium.com/nonstopio/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-i-920252ba1b71"><strong>blog</strong></a>, I explained some of the React Hooks if you didn’t check please read it’s better to understand in depth of each React Hooks, In this blog, I will continue exploring one of the important React Hooks which is useReducer().</p><h4>useReducer<strong>()</strong></h4><p>useReducer() is a React Hook that lets you add a reducer to your component. the usage of the useReducer() is the same as a useState() <br>when there is a more complex to handling or managing the states it’s better to use useReducer() simple words useReducer() helps to manage complex state logic in React applications. Let’s explore more in-depth about useReducer()</p><p><strong>Syntax of the </strong><strong>useReducer()</strong></p><pre>const [state, dispatch] = useReducer(reducer, initialState, initFunc?) </pre><p>useReducer() accepts a reducer function as its first parameter and the initial state as the second. useReducer() returns an array that holds the current state value and a dispatch function to which you can pass an action and later invoke it.<br>If you don’t pass a third argument, it will take the second argument as the initial state. The third argument, which is the initFunc function, is optional. This pattern also follows one of the golden rules of Redux state management: the state should be updated by emitting actions. Never write directly to the state.</p><ol><li><strong>Why to use the </strong>useReducer <strong>? <br> </strong>useReducer() is designed to handle complex state logic that may require multiple actions to be performed on the state. It provides a more structured approach to state management that can help to keep the code organized and maintainable, especially as the complexity of the state and actions increases.<br>useReducer() can be used to manage states across multiple components, making it an excellent choice for global state management. This can help prevent the need for prop drilling or other complex solutions for sharing the state between components.</li><li><strong>When to use the </strong>useReducer <strong>?<br></strong>when the type of the state is an object or array, when there is Complicated business logic that is more suitable for a reducer function, and Different properties tied together that should be managed in one state object.</li></ol><p>Let&#39;s see with the example how to use the useReducer()</p><p><strong><em>Using the </em></strong><strong><em>useState() hook</em></strong></p><pre>import { useState } from &quot;react&quot;;<br><br>export default function User2() {<br>  const [user, setUser] = useState({<br>    name: &quot;Jhon&quot;,<br>    age: 20,<br>    qualification: &quot;BE&quot;,<br>    role: &quot;Software Development&quot;,<br>  });<br><br>  function handleButtonClick() {<br>    setUser((previousState) =&gt; ({<br>      ...previousState, // Copy the old fields<br>      ...{ age: previousState.age + 1 },<br>    }));<br>  }<br>  function handleInputChange(e) {<br>    setUser((previousState) =&gt; ({<br>      ...previousState,<br>      ...{ name: e.target.value },<br>    }));<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;input value={user.name} onChange={handleInputChange} /&gt;<br>      &lt;button onClick={handleButtonClick}&gt;Increment age&lt;/button&gt;<br>      &lt;div&gt;Hello, My name is {user.name}.&lt;/div&gt;<br>      &lt;div&gt;<br>        I am &lt;b&gt;{user.age}&lt;/b&gt; old.<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        I am working as &lt;b&gt;{user.role}&lt;/b&gt;.<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>If the logic of our code gets complicated then the setter function can be large and it will be difficult to handle it. Also, we have to take care of returning new items in every setter function using the spreading operator. This becomes very difficult to manage.</p><p>To simplify our lives, we have a useReducer hook to our rescue!</p><p><strong><em>Using the </em></strong><strong>useReducer</strong><strong><em>() hook</em></strong></p><pre>import { useReducer } from &quot;react&quot;;<br><br>function userReducer(state, action) {<br>  switch (action.type) {<br>    case &quot;incremented_age&quot;: {<br>      return {<br>        name: state.name,<br>        age: state.age + 1,<br>      };<br>    }<br>    case &quot;changed_name&quot;: {<br>      return {<br>        name: action.nextName,<br>        age: state.age,<br>      };<br>    }<br>  }<br>  throw Error(&quot;Unknown action: &quot; + action.type);<br>}<br>const initialState = {<br>  name: &quot;Jhon&quot;,<br>  age: 20,<br>  qualification: &quot;BE&quot;,<br>  role: &quot;Software Development&quot;,<br>};<br>export default function User() {<br>  const [user, dispatch] = useReducer(userReducer, initialState);<br><br>  function handleButtonClick() {<br>    dispatch({ type: &quot;incremented_age&quot; });<br>  }<br><br>  function handleInputChange(e) {<br>    dispatch({<br>      type: &quot;changed_name&quot;,<br>      nextName: e.target.value,<br>    });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input value={user.name} onChange={handleInputChange} /&gt;<br>      &lt;button onClick={handleButtonClick}&gt;Increment age&lt;/button&gt;<br>      &lt;div&gt;Hello, My name is {user.name}.&lt;/div&gt;<br>      &lt;div&gt;<br>        I am &lt;b&gt;{user.age}&lt;/b&gt; old.<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        I am working as &lt;b&gt;{user.role}&lt;/b&gt;.<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The above Looks simple and clean. useReducer() is very similar to useState, but it lets us move the state update logic from event handlers into a single function outside of our component.</p><p><strong>The Conclusion<br></strong>useReducer() is an alternative to useState() which gives you more control over the state management and can make testing easier. All the cases can be done with useState() the method, so in conclusion, use the method that you are comfortable with, and it is easier to understand.</p><p>You can check the code <a href="https://codesandbox.io/embed/dsqvw9?view=Editor+%2B+Preview&amp;module=%2Fsrc%2Fuser.js">here</a></p><p><a href="https://codesandbox.io/embed/dsqvw9?view=Editor+%2B+Preview&amp;module=%2Fsrc%2Fuser.js">CodeSandbox</a></p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@vidya.jayagouda"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><h3>References</h3><p><a href="https://react.dev/reference/react/useReducer">React Document</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf4fd5298a2a" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-ii-cf4fd5298a2a">Mastering React Hooks: A Comprehensive Guide to Streamlining Your Component Magic[Part-II]</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Hooks: A Comprehensive Guide to Streamlining Your Component Magic[Part-I]]]></title>
            <link>https://blog.nonstopio.com/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-i-920252ba1b71?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/920252ba1b71</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 10:13:42 GMT</pubDate>
            <atom:updated>2024-01-31T09:41:06.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwahPBaloup2qnIdQoKsJw.png" /></figure><h4>Introduction</h4><p>Hooks were added to React in the 16.8 version. Hooks allow us to access the state in the functional component and other features of the Hooks.<br>Hook allows us to “hook” into the React features like state and lifecycle methods. Let’s Explore the different types of Hooks.</p><h4>1. useState()</h4><p>useState() is a function used to declare the state in the Functional components, It takes the initial state as an argument and returns the array with two elements.<br>We can’t use the useState()inside conditional statements(if, switch, etc), functions, or loops.<br>Let us see how to use useState()an Example</p><pre><br>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br> // initialize the state <br> const [countValue, setCountValue] = useState(0);<br><br> // to increment the count value<br> const incrementCount = () =&gt; {<br>  setCountValue(countValue + 1);<br> };<br><br> // to decrement the count value<br> const decrementCount = () =&gt; {<br>  countValue &gt; 0 ? setCountValue(countValue - 1) : null;<br>  // when you want to decrement countValue with based on the previous value use the<br>  // callback function in the setCountValue<br>  // setCountValue((prevCountValue) =&gt; {<br>  //  prevCountValue - 1;<br>  // });<br>  // countValue = 2<br>  setCountValue(countValue - 1);<br>  setCountValue(countValue - 1);<br>  // output : 1<br> };<br> return (<br>  &lt;div style={{ display: &#39;flex&#39;, alignItems: &#39;center&#39;, gap: &#39;24px&#39; }}&gt;<br>   &lt;button<br>    style={{ backgroundColor: &#39;red&#39;, color: &#39;white&#39;, fontSize: &#39;18px&#39; }}<br>    onClick={decrementCount}&gt;<br>    -<br>   &lt;/button&gt;<br>   &lt;p style={{ color: &#39;#000&#39;, fontSize: &#39;24px&#39;, fontWeight: 700 }}&gt;<br>    {countValue}<br>   &lt;/p&gt;<br>   &lt;button<br>    onClick={incrementCount}<br>    style={{ backgroundColor: &#39;green&#39;, color: &#39;white&#39;, fontSize: &#39;18px&#39; }}&gt;<br>    +<br>   &lt;/button&gt;<br>  &lt;/div&gt;<br> );<br>}<br><br>export default Counter;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*SCp2T02iQTeuESf067fR7Q.png" /></figure><h4>2. useEffect()</h4><p>useEffect() is a hook in React, that allows you to perform side effects in your functional components. Side effects can include things like data fetching, subscriptions, manual DOM manipulations, and more. The useEffect hook is used to manage these side effects in a way that is consistent with the React component lifecycle.<br>The useEffect()function takes two arguments: a function (usually called the “effect”) that contains the side effects, and an array of dependencies (optional). The function is executed whenever any item in the dependencies array changes.</p><p>Let us see how to use useEffect() an Example</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>function Counter() {<br> // initialize the state <br> const [countValue, setCountValue] = useState(0);<br><br> const incrementCount = () =&gt; {<br>  setCountValue(countValue + 1);<br> };<br><br> const decrementCount = () =&gt; {<br>  countValue &gt; 0 ? setCountValue(countValue - 1) : null;<br>  // countValue = 2<br>  setCountValue(countValue - 1);<br>  setCountValue(countValue - 1);<br>  // output :- 1<br>  <br> };<br><br> // useEffect:-<br> // 1. change in the any state<br> // 2. call the asynchronous function like calling the API&#39;s etc..<br> // 3. If no dependency added then the useEffect will run at least once when the component mount<br> // useEffect(() =&gt; {<br> //  // write the code you want to run<br> //  // Optional return function:-whenever you want clean are remove any function when this component is unmount<br> //  // 1 . when there is no dependency then this function will run at unmount of this component , to clean up<br> //  // return () =&gt; {<br> //  //  console.log(&#39;clean me,  when this component is unMount &#39;);<br> //  // };<br> // }, []); // dependency array<br><br> useEffect(() =&gt; {<br>  console.log(&#39;Count Value is:-&#39;, countValue);// Count value is :- 2<br> }, [countValue]);<br> return (<br>  &lt;&gt;<br>   &lt;b style={{ textAlign: &#39;center&#39;, fontSize: &#39;30px&#39;, margin: &#39;20px&#39; }}&gt;<br>    Counter Project<br>   &lt;/b&gt;<br>   &lt;div style={{ display: &#39;flex&#39;, alignItems: &#39;center&#39;, gap: &#39;24px&#39; }}&gt;<br>    &lt;button<br>     style={{ backgroundColor: &#39;red&#39;, color: &#39;white&#39;, fontSize: &#39;18px&#39; }}<br>     onClick={decrementCount}&gt;<br>     Decrement<br>    &lt;/button&gt;<br>    &lt;p style={{ color: &#39;#000&#39;, fontSize: &#39;24px&#39;, fontWeight: 700 }}&gt;<br>     {countValue}<br>    &lt;/p&gt;<br>    &lt;button<br>     onClick={incrementCount}<br>     style={{<br>      backgroundColor: &#39;green&#39;,<br>      color: &#39;white&#39;,<br>      fontSize: &#39;18px&#39;,<br>     }}&gt;<br>     Increment<br>    &lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/&gt;<br> );<br>}<br><br>export default Counter;<br></pre><h4><strong>3. useCallback()</strong></h4><p>useCallback is the react hook that lets you cache a function definition between re-rendering. It takes two arguments:- the function to cache and an array of dependencies.<br>useCallback() is used more to improve the performance optimizations of the project like when we are calling the child component inside the parent component and passing any function to a child component. <br>Whenever there is a change in the parent component props or state the child component will be rendered to prevent this will be used useCallback() to prevent unnecessary re-creation of functions on each render, which can help to prevent unnecessary renders of child components.</p><p>Let&#39;s see how to use useCallback() with Example</p><pre><br>//User.jsx<br>import { useCallback, useState } from &#39;react&#39;;<br><br>import SearchInput from &#39;./searchInput&#39;;<br><br>const allUsers = [&#39;john&#39;, &#39;alex&#39;, &#39;george&#39;, &#39;simon&#39;, &#39;james&#39;];<br><br>export default function Lists() {<br> const [users, setUsers] = useState(allUsers);<br><br>  // useCallback (()=&gt; {}, [])<br> const handleSearch = useCallback(<br>  (text) =&gt; {<br>   console.log(users[0]);<br><br>   const filteredUsers = allUsers.filter((user) =&gt; user.includes(text));<br>   setUsers(filteredUsers);<br>  },<br>  [users]<br> );<br><br> return (<br>  &lt;div className=&#39;tutorial&#39;&gt;<br>   &lt;b style={{ textAlign: &#39;center&#39;, fontSize: &#39;30px&#39;, margin: &#39;20px&#39; }}&gt;<br>    List of Users<br>   &lt;/b&gt;<br>   &lt;div className=&#39;align-center mb-2 flex&#39;&gt;<br>    &lt;button<br>     style={{<br>      backgroundColor: &#39;#6600FF&#39;,<br>      color: &#39;#ffffff&#39;,<br>      fontSize: &#39;18px&#39;,<br>     }}<br>     onClick={() =&gt; setUsers(shuffle(allUsers))}&gt;<br>     Shuffle<br>    &lt;/button&gt;<br><br>    &lt;SearchInput onChange={handleSearch} /&gt;<br>   &lt;/div&gt;<br>   &lt;ol type=&#39;1&#39;&gt;<br>    {users.map((user) =&gt; (<br>     &lt;li key={user}&gt;{user}&lt;/li&gt;<br>    ))}<br>   &lt;/ol&gt;<br>  &lt;/div&gt;<br> );<br>}Example</pre><pre>// SearchInput.jsx<br>import { memo } from &#39;react&#39;;<br><br>function SearchInput({ onChange }) {<br> console.log(&#39;Search rendered!&#39;);<br><br> return (<br>  &lt;input<br>   style={{ marginLeft: &#39;20px&#39;, width: &#39;200px&#39;, height: &#39;40px&#39; }}<br>   type=&#39;text&#39;<br>   placeholder=&#39;Search users...&#39;<br>   onChange={(e) =&gt; onChange(e.target.value)}<br>  /&gt;<br> );<br>}<br><br>export default memo(SearchInput);</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*U8Pvfaz1BrpbtVqlvRX0dw.png" /></figure><p>In the above Example. We have the User and SearchInput components and the SearchInput component is the child component of the Users.memo is used to skip re-rendering SearchInputwhen its props are unchanged.<br><strong>Let’s see without </strong><strong>useCallback() a scenario.</strong><br>1. Whenever the user clicks on the Shuffle button there is a change in the users state then the components re-render and the SearchInput also renders <br>2. Also we are wrapping SearchInput component with memo() to avoid unnecessary renders but still SearchInput re-render because wherever there is a change in any props in the User the function will create fresh in the dom again so to avoid this we can use the <strong>useCallback() .</strong></p><p><strong>Let’s see </strong><strong>useCallback() a scenario.<br></strong>Whenever the user clicks on the Shuffle button there is a change in the users state then the User component re-render but SearchInput will not render because there is no change in the previous handleSearch function and current handleSearch because we have added the <strong>useCallback() .<br></strong>so it will memorize this function in the memory when there is any change in this function then that will be memorized in the memory or else it will remain the same as the previous function. This will improve the performance of the project.</p><h4><strong>4. useRef()</strong></h4><p>useRef() is a React Hook that lets you reference a value that’s not needed for rendering. Unlike state ref does not trigger the re-render of the component because React is not aware of when you change it because a ref is a plain JavaScript object.<br><strong>1</strong>. refs are not used to read any value in the JSX because whenever there is a change in the ref value the updated value is not reflected in UI because react will not re-render the component when change in the ref value.<br>Let see with an Example.</p><pre>import { useRef, useState } from &#39;react&#39;;<br><br>export default function RefExample() {<br> const [count, setCount] = useState(0);<br> const countRef = useRef(0);<br><br> const handleIncrement = () =&gt; {<br>  //setCount(count + 1);<br>  countRef.current++;<br><br>  console.log(&#39;State:&#39;, count); // 0<br>  console.log(&#39;Ref:&#39;, countRef.current); // 1<br> };<br><br> return (<br>  &lt;div className=&#39;tutorial&#39;&gt;<br>   &lt;b&gt; Count: {count}&lt;/b&gt;<br>   &lt;button<br>    style={{<br>     marginLeft: &#39;10px&#39;,<br>     backgroundColor: &#39;green&#39;,<br>     color: &#39;white&#39;,<br>     fontSize: &#39;18px&#39;,<br>    }}<br>    onClick={handleIncrement}&gt;<br>    Increment<br>   &lt;/button&gt;<br>   &lt;div&gt;{`The count state value is:  ${count}`}&lt;/div&gt;<br>   &lt;div&gt;{`The count ref value is: ${countRef.current}`}&lt;/div&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAFZun0igWypBkKWafWtUg.png" /></figure><p>2. ref is mostly used when we want to directly access the HTML dom elements and functions on those elements.</p><pre>import { useEffect, useRef } from &#39;react&#39;;<br><br>export function RefExample2() {<br> const inputRef = useRef(null);<br><br> useEffect(() =&gt; {<br>  inputRef.current?.focus();<br> }, []);<br><br> return (<br>  &lt;div className=&#39;tutorial&#39;&gt;<br>   &lt;h1&gt;React with Ref&lt;/h1&gt;<br>   &lt;input<br>    style={{ width: &#39;200px&#39;, height: &#39;40px&#39; }}<br>    ref={inputRef}<br>    type=&#39;text&#39;<br>    placeholder=&#39;Type something...&#39;<br>   /&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*usg1Falvfp5N6nhR_XGgdQ.png" /></figure><h4>5.useId()</h4><p>useId() is a React Hook for generating unique IDs that can be passed to accessibility attributes.useId() does not take any parameters.<br>useId returns a unique ID string associated with this particular useId call in this particular component.<br>useId() <strong>should not be used to generate keys</strong> in a list.</p><pre>import { useId } from &#39;react&#39;;<br><br>function PasswordField() {<br>  const passwordHintId = useId();<br>}</pre><h3>Takeaways</h3><p>I hope you learned something from this (long) post and felt at least a bit more confident about working with hooks. Please reach out to me with any feedback as I’m sure there are things I have overlooked or could have explained better.<strong> Stay tuned for Part [II] </strong>of the React hooks for building and understanding in-depth about Hooks in the React Thank you!.<br>you can check the source code of these hooks in my GitHub repository.</p><p>You can check the code here</p><p><a href="https://codesandbox.io/p/github/VidyaGouda17/Mastering-React-Hooks/main?embed=1&amp;file=%2Fsrc%2FApp.jsx">https://codesandbox.io/p/github/VidyaGouda17/Mastering-React-Hooks/main?embed=1&amp;file=%2Fsrc%2FApp.jsx</a></p><p><a href="https://github.com/VidyaGouda17/Mastering-React-Hooks">GitHub - VidyaGouda17/Mastering-React-Hooks</a></p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@vidya.jayagouda"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><h3>References</h3><ul><li><a href="https://react.dev/reference/react/hooks">React Document</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=920252ba1b71" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/mastering-react-hooks-a-comprehensive-guide-to-streamlining-your-component-magic-part-i-920252ba1b71">Mastering React Hooks: A Comprehensive Guide to Streamlining Your Component Magic[Part-I]</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronous and Asynchronous in JavaScript]]></title>
            <link>https://blog.nonstopio.com/synchronous-and-asynchronous-in-javascript-95445564d435?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/95445564d435</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 02:32:59 GMT</pubDate>
            <atom:updated>2023-10-31T04:52:51.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0Rci0W4rslc2rjr0dh6yg.png" /></figure><h4>Introduction</h4><p>JavaScript, the language that powers the web, is known for its versatility. In web development, understanding how to manage asynchronous and synchronous operations is crucial. These operations can make or break the user experience of your web application. In this article, we’ll explore the concepts of asynchronous and synchronous operations in JavaScript, how they work, and when to use each for optimal results.</p><h4>Synchronous Operations: Blocking, sequence</h4><p>In JavaScript, synchronous operations are straightforward and follow a simple rule: one thing at a time. When a function executes synchronously, it blocks the execution of any other code until it completes. Imagine JavaScript as an orchestra where each musician plays their part sequentially, following the conductor’s beat.</p><p>Consider this simple synchronous code that calculates the sum of two numbers:</p><pre>const addNumber = (a, b) =&gt;<br>{<br>  return a + b;<br>};<br><br>const result = addNumber( 10, 4 );<br>console.log(result); // Output: 14</pre><p>In this example, the addNumber function executes synchronously, and the result is calculated before moving on to the next line of code.</p><h4>Asynchronous Operations: Non-blocking, event-driven programming model where multiple operations can co-occur.</h4><p>Asynchronous operations, on the other hand, are like a dance performance, where multiple tasks can be executed simultaneously. In JavaScript, asynchronous operations allow you to execute code without blocking the main thread, ensuring a responsive user interface. Common asynchronous tasks include making network requests, reading files, or handling user interactions.</p><p>The most common way to achieve asynchrony in JavaScript is by using callbacks, Promises, and async/await.</p><p>Let’s look at a simple example using some asynchronous functions like setTimeout(), and clearTimeout().</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Async Operations in Javascript&lt;/h1&gt;<br>  &lt;button id =&#39;stopped&#39;&gt;Click me &lt;/button&gt;<br>  &lt;script&gt;<br>    //browser functions will get setTimeOut() , setInterval(), clearTimeOut() clearInterval(), <br>    /*<br>    1) setTimeOut(functionRef, delay, param1, param2) =&gt; this sets a timer to execute the function when the timer expires<br>    2) clearInterval (functionRef) =&gt; This method clears a timer set with the setTimeout() method.<br><br>    */<br>   const sayHello = () =&gt;{<br>    console.log(&quot;hi javascript&quot;)<br>   }<br><br>    setTimeout(sayHello, 1000);<br>    const changeText = () =&gt; {<br>      document.querySelector(&#39;h1&#39;).innerHTML = &quot;Javascript is best.&quot;;<br>    }<br>   const changeMe = setTimeout(changeText, 3000);<br><br>    document.querySelector(&#39;#stopped&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>      clearTimeout(changeMe);<br>      console.log(&#39;Stopped&#39;)<br>    })<br>    <br>    const changeTextWithParam = (p1, p2) =&gt; {<br>      document.querySelector(&#39;h1&#39;).innerText = `say ${p1}, ${p2}`<br>    }<br>    // setTimeOut with the callback function , timer and the parameters <br>    const changeMeWithParam = setTimeout(changeTextWithParam, 3000, &quot;Hello&quot; , &quot;Javascript&quot;);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Let’s look at a simple example using some asynchronous functions like setInterval(), and clearInterval().</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Async Operations in Javascript&lt;/h1&gt;<br>  &lt;button id =&#39;start&#39;&gt;Start me &lt;/button&gt;<br>    &lt;button id =&#39;stop&#39;&gt;Stop me &lt;/button&gt;<br><br>  &lt;script&gt;<br>    //browser functions will get  setInterval(), clearInterval(), <br>    /*<br>    1) setInterval(functionRef, delay, param1, param2) =&gt; this sets a timer to execute the function <br>              again and again <br>    2) clearInterval (functionRef) =&gt; to cancel the interval will use the clearInterval <br>    */<br><br>    const startClicked = () =&gt;{<br>      document.querySelector(&#39;#start&#39;).addEventListener(&#39;click&#39; , () =&gt; {<br>      console.log(&quot;Button start&quot;, Date.now());<br>      document.querySelector(&#39;h1&#39;).innerText = &quot;Started &quot;<br>        console.log(&quot;Button start&quot;, Date.now())<br>      })<br>    }<br>    const clearTime = setInterval(startClicked , 2000);<br>   <br>      document.querySelector(&#39;#stop&#39;).addEventListener(&#39;click&#39; , () =&gt;{<br>      document.querySelector(&#39;h1&#39;).innerHTML = &quot;Stopped&quot;<br>        console.log(&quot;Button stop&quot;);<br>        clearInterval(clearTime)<br>      })<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Choosing Between Synchronous and Asynchronous Operations</h4><p>The choice between synchronous and asynchronous operations depends on the specific task and the impact on the user experience:</p><ol><li><strong>Synchronous operations </strong>are suitable for tasks that must be completed before moving on. For instance, when calculating a result that’s needed immediately or for simpler operations that won’t noticeably impact performance.</li><li><strong>Asynchronous operations</strong> are ideal for tasks that can be performed in the background without affecting the user interface. This includes network requests, file I/O, or any operation that might take some time to complete.</li></ol><p>For example, when building a web page, you wouldn’t want synchronous operations to freeze the user interface while loading large images. Instead, you’d use asynchronous operations to load resources in the background, keeping the page responsive.</p><h4><strong>Challenges in Asynchronous Operations</strong></h4><p>While asynchronous operations are essential for a smooth user experience, they can introduce complexity. Managing callbacks and ensuring the order of execution can be challenging. This is where Promises and async/await come to the rescue, providing a cleaner and more predictable way to handle asynchrony.</p><h4><strong>Conclusion</strong></h4><p>Mastering asynchronous and synchronous operations in JavaScript is a fundamental skill for any web developer. Understanding when to use each type of operation can significantly impact the user experience of your web applications. , JavaScript offers the tools you need to create a harmonious web experience for your users.</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@vidya.jayagouda"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><h4>References</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducin</a>g</li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous</a></li><li><a href="https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/1/introduction">Course:</a> <a href="https://www.youtube.com/watch?v=zgt5oTD3rRc">Async and Sync In javascript By Chai aur code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95445564d435" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/synchronous-and-asynchronous-in-javascript-95445564d435">Synchronous and Asynchronous in JavaScript</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises In Javascript]]></title>
            <link>https://blog.nonstopio.com/promises-in-javascript-ca18ae4e8594?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca18ae4e8594</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 02:32:27 GMT</pubDate>
            <atom:updated>2023-10-31T02:32:27.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUJ1oIkmsxVUE6o9t7AHzg.png" /></figure><h4>Introduction</h4><p>In the world of JavaScript, asynchronicity reigns supreme. Many operations, such as network requests and file I/O, are inherently asynchronous. In the past, handling these asynchronous operations could be a daunting task, often leading to callback hell and hard-to-maintain code. However, the introduction of Promises has changed the game, making it easier than ever to manage asynchronous operations. In this article, we will dive deep into Promise operations in JavaScript, mastering this powerful tool.</p><h4>What Are Promises?</h4><p>Before we get into the Promise operations, let’s start with the basics. A Promise is an object that represents a value that might not be available yet but will be at some point in the future. Promises are used to handle asynchronous operations, such as fetching data from an API, reading a file, or making a database query.</p><p><strong>A Promise can be in one of three states</strong>:</p><ol><li><strong>Pending</strong>: The initial state, representing the promise’s state before it’s resolved or rejected.</li><li><strong>Fulfilled</strong>: The state indicating that the asynchronous operation was completed successfully, resulting in a resolved promise.</li><li><strong>Rejected</strong>: The state indicating that the asynchronous operation encountered an error or was unsuccessful, leading to a rejected promise.</li></ol><h4>Creating Promises</h4><p>You can create a Promise using the Promise constructor, which takes a single function as an argument. This function, often referred to as the “executor,” has two parameters: resolve and reject. Inside this function, you perform the asynchronous operation and call resolve when it&#39;s successful or reject when an error occurs.</p><h4>Consuming Promises</h4><p>Once you’ve created a Promise, you need to consume it. Promises provide two methods for handling the resolved or rejected value: then and catch.</p><p>The then method is used to specify what should happen when the promise is fulfilled (resolved). It takes two optional callback functions: one for success and another for failure (rejection) i.e catch.</p><p>Let’s see the example:</p><ol><li>In this example will learn how to create a promise and how to consume the promise.</li></ol><pre>// create a promise <br>const promiseOne = new Promise( ( resolve, reject ) =&gt;<br>{<br>  // do the async operation like calling a API , db connections etc<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async operation completed&quot; );<br>    // to connect the then and promise we need to call resolve()<br>    resolve();<br>  }, 1000 );<br>} );<br><br>//consume the promise<br>promiseOne.then( () =&gt;<br>{<br>  console.log( &quot;Promise executed suscussefuly.&quot; );<br>} ).catch( ( error ) =&gt;<br>{<br>  console.log( &quot;Promise executed unSuscussefuly.&quot; );<br>} );<br><br>// we can create a promise like this also <br>new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async operation completed&quot; );<br>    // to <br>    resolve();<br>  }, 1000 );<br>} ).then( () =&gt;<br>{<br>  console.log( &quot;Promise executed suscussefuly.&quot; );<br>} ).catch( () =&gt;<br>{<br>  console.log( &quot;Promise executed unSuscussefuly.&quot; );<br>} );<br><br>//</pre><p>2. In this example will learn how to create a promise and how to read the data when the resolve function calls in the promise.</p><pre>// create a promise and consume the promises and learn how to read the data from the resolve<br><br>const promiseTwo = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async operation 2&quot; );<br>    resolve( {<br>      userName: &#39;Vidya&#39;,<br>      role: &#39;Software Developer&#39;,<br>      company: &#39;Nonstopio Technologies&#39;<br>    } );<br>  }, 1000 );<br>} );<br><br>promiseTwo.then( ( user ) =&gt;<br>{<br>  console.log( &quot;response&quot;, user );<br>} );</pre><p>3. In this example will learn how to read the error when the promise is rejected.</p><pre>// lets learn when promise is rejected how to read the error<br>const promiseFour = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async operation 4&quot; );<br>    let error = true;<br>    if ( !error )<br>    {<br>      resolve( {<br>        userName: &#39;Vidya&#39;,<br>        role: &#39;Software Developer&#39;,<br>        company: &#39;Nonstopio Technologies&#39;<br>      } );<br>    } else<br>    {<br>      reject( &quot;Error: Something went wrong&quot; );<br>    }<br>  } );<br>}, 1000 );<br><br>promiseFour.then( ( user ) =&gt;<br>{<br>  console.log( &quot;response&quot;, user );<br>} ).catch( ( error ) =&gt;<br>{<br>  console.log( &quot;Caught an Error&quot;, error );<br>} );</pre><p>4. <strong>Promise Chaining</strong>: Promises become even more powerful when you chain them together. Chaining allows you to sequence multiple asynchronous operations. When one operation is completed, you can start the next one. This results in cleaner and more maintainable code.</p><p>Let us learn promise changing from the example.</p><pre>// lets learn  promise chaining and finally block<br>const promiseFive = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async operation 5&quot; );<br>    let error = false;<br>    if ( !error )<br>    {<br>      resolve( {<br>        userName: &#39;Vidya&#39;,<br>        role: &#39;Software Developer&#39;,<br>        company: &#39;Nonstopio Technologies&#39;<br>      } );<br>    } else<br>    {<br>      reject( &quot;Error: Something went wrong&quot; );<br>    }<br>  } );<br>}, 1000 );<br><br>promiseFive.then( ( user ) =&gt;<br>{<br>  return user?.userName;<br>} ).then( ( userName ) =&gt;<br>{<br>  console.log( &quot;User Name: &quot;, userName );<br>} ).catch( ( error ) =&gt;<br>{<br>  console.log( &quot;Caught an Error&quot;, error );<br>} ).finally( () =&gt;<br>{<br>  // this will execute either promise is resolved or rejected <br>  console.log( &quot;The promise is either resolve or rejected&quot; );<br>} );</pre><p>5.<strong> Async and await in Promises</strong></p><p>Async/Await makes it easier to write promises. The keyword ‘async’ before a function makes the function return a promise, always. The keyword await is used inside async functions, which makes the program wait until the Promise resolves or is rejected.</p><p>let’s learn how the async and await are used in promise with example.</p><pre>// the promise with async and wait <br>const promiseSix = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    console.log( &quot;Async Operation 6&quot; );<br>    let error = true;<br>    if ( !error )<br>    {<br>      resolve( {<br>        userName: &#39;Vidya&#39;,<br>        role: &#39;Software Developer&#39;,<br>        company: &#39;Nonstopio Technologies&#39;<br>      } );<br>    } else<br>    {<br>      reject( &quot;Error: Something went wrong&quot; );<br>    }<br>  }, 1000 );<br>} );<br><br>const consumePromise = async () =&gt;<br>{<br>  // try catch block is used to handle resolve and to catch the error   <br>  try<br>  {<br>    const response = await promiseSix;<br>    console.log( response, &quot;response&quot; );<br>  } catch ( error )<br>  {<br>    console.log( `Error: ${ error }` );<br>  }<br>};<br><br>consumePromise(</pre><p>6. <strong>Parallel Promises</strong></p><p>There are situations where you need to perform multiple asynchronous operations in parallel and wait for all of them to complete before proceeding. JavaScript provides the Promise.all method for such cases. It takes an array of Promises and returns a new Promise that fulfills with an array of resolved values once all the input Promises have been fulfilled.</p><pre>// promise all <br>const promise1 = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    resolve( {<br>      userName: &#39;Vidya&#39;,<br>      gender: &#39;female&#39;<br>    } );<br>  }, 1000 );<br>} );<br>const promise2 = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    let error = false;<br>    if ( !error )<br>    {<br>      resolve( {<br>        hobbies: [ &#39;reading&#39;, &#39;traveling&#39; ]<br>      } );<br>    } else<br>    {<br>      reject( &quot;promise two rejected&quot; );<br>    }<br>  }, 1000 );<br>} );<br>const promise3 = new Promise( ( resolve, reject ) =&gt;<br>{<br>  setTimeout( () =&gt;<br>  {<br>    let error = false;<br>    if ( !error )<br>    {<br>      resolve( {<br>        role: &#39;developer&#39;,<br>        company: &#39;Nonstopio&#39;<br>      } );<br>    } else<br>    {<br>      reject( &quot;promise three rejected&quot; );<br>    }<br>  }, 1000 );<br><br>} );<br><br>Promise.all( [ promise1, promise2, promise3 ] ).then( ( user ) =&gt;<br>{<br>  console.log( user );<br>} ).catch( ( error ) =&gt;<br>{<br>  console.log( `Error: ${ error }` );<br>} )</pre><h4>Conclusion</h4><p>Promises have revolutionized how we handle asynchronous operations in JavaScript. They provide a clear and elegant way to work with asynchronous code, avoiding callback hell and making our code more readable and maintainable. With chaining and Promise.all, we can easily handle complex asynchronous flows. As you dive deeper into JavaScript development, mastering promises is a fundamental skill that will serve you well in building robust and efficient applications.</p><p>Remember that in modern JavaScript, you also have access to async/await, which simplifies working with Promises even further. Promises are a stepping stone to understanding the asynchronous nature of JavaScript, and they remain a valuable tool in your toolkit. So, go ahead, embrace Promises, and unlock the true potential of asynchronous JavaScript development.</p><blockquote>Here to make the community stronger by sharing our knowledge. <a href="https://medium.com/@vidya.jayagouda">Follow me</a><em> </em>and <a href="https://medium.com/nonstopio">my team</a> to stay updated on the latest and greatest in the web &amp; mobile tech world.</blockquote><h4>References</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Mdn Doc</a></li><li><a href="https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/1/introduction">Course:</a><a href="https://www.youtube.com/watch?v=NJwRQgsu1Q8&amp;t=2553s"> Promise in javascript | chai aur #javascript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca18ae4e8594" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/promises-in-javascript-ca18ae4e8594">Promises In Javascript</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Set Up The StoryBook In React [Part -I]]]></title>
            <link>https://blog.nonstopio.com/how-to-set-up-the-storybook-in-react-part-i-99d2ce22ab4f?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/99d2ce22ab4f</guid>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 05:39:23 GMT</pubDate>
            <atom:updated>2023-07-17T05:39:23.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NirB0QTkYiN3vN2SLgvzog.jpeg" /><figcaption>Credits: <a href="https://www.aceinfoway.com/">https://www.aceinfoway.com</a></figcaption></figure><p><strong>What is StoryBook and Why we should use Storybook?</strong></p><p>Storybook is an Open-source tool to develop and test the user interface components in isolation. This means developers aren’t distracted by plenty of data, business logic, or unfinished APIs. Storybook helps us to concentrate on developing the UI with user cases and save these cases to revisit during QA and review.<br>We can add the addOns to get plenty of features like prototyping, documentation, and testing.<br>We can share a storybook to collaborate on UI development with the Designers, Product managers, and other developers.<br>Storybook provides us with a simple way to browse the component and their use cases in one place And it’s easy to drop components we find right into our Application.<br>Storybook supports a wide range of UI frameworks and libraries, including React, Vue, Angular, and many others. It integrates with popular tools like webpack and Babel, allowing seamless integration into existing development workflows.</p><h4><strong>How to use the Storybook in React?</strong></h4><h4>Create a react application by using the below command</h4><pre>npx create-react-app my-app</pre><h4>To initialize the StoryBook into your project use the below command</h4><pre>npx storybook@latest init </pre><p>Once you run this command in your App storybook will look into your project dependencies during its installation and provide the best configuration for your project setup.<br>By using the above command will make the following changes in your App.</p><p>1.📦 Install the required dependencies.</p><p>2. 🛠 Set up the necessary scripts to run and build Storybook.</p><p>3.🛠 Add the default Storybook configuration.</p><p>4.📝 Add some boilerplate stories to get you started.</p><p>5.📡 Set up telemetry to help us improve Storybook.</p><h4>To check the App is working fine run the React app</h4><pre>npm start</pre><h4>To run the storybook use this command</h4><pre>npm run storybook</pre><p>It will start Storybook locally and output the address. Depending on your system configuration, it will automatically open the address in a new browser tab, and you’ll be greeted by a welcome screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38gCdIGzKyrarXeCjhjrVQ.png" /><figcaption>credits: <a href="https://storybook.js.org/docs/react/get-started/install/">https://storybook.js.org/docs/react</a></figcaption></figure><p>The following changes will be done to your Application <br>1. .story the folder will be created in your application which has main.js and preview.js files.</p><p>I)main.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8goKIQ6Utq5ENdF78SFeQ.png" /></figure><p>As you can observe in the above image in main.js the file we have lots of configurations for the storybook let&#39;s see what they define: <br>a) Inside sotires array we can see the storybook components can be written with the extension as name.stories.mdx or name.stories.js or name.stories.jsx or name.stories.ts when you run the storybook command the storybook will look at the file which has the above extension file name then it will consider these are the storybook components and then according to your project structure the component will be displayed in the storybook.<br>b) addons : This array lists the Storybook addons you want to use. Addons are extensions that provide additional functionality to Storybook. The addons listed here include &quot;@storybook/addon-links&quot;, &quot;@storybook/addon-essentials&quot;, &quot;@storybook/addon-interactions&quot;, and &quot;@storybook/preset-create-react-app&quot;. These are commonly used addons for adding interactivity, links, and other essential features to Storybook.<br>Addons extend Storybook with features and integrations that are not built into the core. Most Storybook features are implemented as addons. The <a href="https://storybook.js.org/docs/react/addons/addons-api">addon API </a>makes it easy for you to configure and customize Storybook in new ways. There are countless addOns made by the community that unlocks time-saving workflows.<br>c) frmework : Specifies the framework used for the components in Storybook. In this case, it’s set to, indicate that you&#39;re using storybook in React as the framework.<br>d)core.builder: Specifies the builder used by Storybook. Builders are responsible for bundling and building the components. Here, &quot;@storybook/builder-webpack5&quot; is used, which indicates that Webpack 5 is the chosen builder.</p><p>II ) preview.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vpa0QSrxtaR2KfvdMKTKGQ.png" /></figure><p>As you can observe in the above image in preview.js the file we have lots of configurations for the storybook let&#39;s see what they define:<br>a)actions: This configuration controls how actions (event handlers) are displayed in the Storybook UI. The argTypesRegex property specifies a regular expression pattern that matches the names of action arguments. In this case, it matches any prop name that starts with &quot;on&quot; followed by an uppercase letter. For example, onClick or onSubmit.<br>b)controls: This configuration controls how controls (props) are displayed in the Storybook UI. The matchers property defines regular expression patterns for different types of rules. It helps Storybook identify the appropriate control type for each prop. In this example, there are two matches defined:<br>1)color: /(background|color)$/i: This matcher is used to identify props related to color. It matches prop names that end with &quot;background&quot; or &quot;color&quot;, case-insensitively. For example, backgroundColor or textColor.<br>2)date: /Date$/: This matcher is used to identify props related to dates. It matches prop names that end with &quot;Date&quot;. For example, startDate or endDate.<br>These configuration options allow you to customize how actions and controls are displayed in the Storybook UI, making it easier to interact with and explore your UI components during development. <br>When you want to apply any properties which should apply to the entire storybook application we can configure the property inside the preview.js it will be applicable to the entire project.</p><p>3) stories storybook components will be created inside the stories folder in your app structure file and Storybook will provide you some default components while you init the storybook in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLr0TNfdIEmenonmlCz81Q.png" /></figure><p>In the above Image we can see the storybook by default provides some default components that are Button.stories.jsx , Header.stories.jsx other files also.</p><h4>Conclusion</h4><p>The storybook is like One time if you build your own components and you can use these components N number of times in yours. Storybook has quickly gained popularity with developers, and it’s easy to see why. The ability to work on isolated components in a clean interface is a huge time-saver, and the ability to visually test your code is also something too good to pass by. With its simple interface and wide range of features, you can quickly put together prototypes or entire UIs without having to worry about setting up a complex development environment.<br>If you’ve used Storybook already, I’d love to hear what you think in the comments.</p><h4>Note :</h4><p>In this story, I have explained a basic about what is storybook and how to set up the storybook in the react so I mentioned it as Part-I <br>In my next medium stories, I will explain more features of the storybook, please Stay Tuned and please Follow Me and My team to support me to write more Medium Stories. …please refer to any stories in our publication <a href="https://medium.com/nonstopio/advanced-javascript-features-2fe8108ab4d3">here</a>.</p><p>Here to make the community stronger by sharing knowledge and experience. <a href="https://medium.com/@vidya.jayagouda">Follow me</a> and <a href="https://blog.nonstopio.com/">My team</a> to stay updated on the latest and greatest in the tech world.</p><h4>References</h4><p><a href="https://storybook.js.org/docs/react/get-started/install/">https://storybook.js.org/docs/react/get-started/install/</a><br><a href="https://www.youtube.com/@chromaticui/videos">https://www.youtube.com/@chromaticui/videos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99d2ce22ab4f" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/how-to-set-up-the-storybook-in-react-part-i-99d2ce22ab4f">How To Set Up The StoryBook In React [Part -I]</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common & Useful Git Commands]]></title>
            <link>https://blog.nonstopio.com/git-commands-7b16b0335a32?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b16b0335a32</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 04:13:58 GMT</pubDate>
            <atom:updated>2023-03-20T03:10:51.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Vbbgb1GWEFgbuO4vbaqcxg.jpeg" /><figcaption>Credits: Google</figcaption></figure><p>Git is one of the most commonly used version control systems. However, it can be daunting and tricky at first with its many commands and workflows. It can be easy to get lost in the world of Git, with lines of merge conflict errors and unintended changes, Git can really be a nightmare for those new to it. And I had a hard time understanding it at first, and I’m sure some of you are still a bit lost.</p><p><strong>Introduction to Git Terminologies<br>1. Clone: “</strong>It is used to make a copy of the target repository or clone it.”</p><p><strong>2. Branch: “</strong>A branch is an active area of development in Git. The most recent commit shows the tip of the branch.”</p><p><strong>3. Checkout: “ </strong>It is used to switch between branches in a repository.”</p><p><strong>4. Diff: “</strong>A Diff is a difference in changes between two Commits, or saved changes.”</p><p>5. <strong>Fetch: “</strong>It means getting the latest changes in the branch and the local/remote repository.”</p><p><strong>6. Fork: “ </strong>By Forking the repository, you will be able to add Commits and create Pull Requests.”</p><p><strong>7. Merge: “ </strong>To bring out the content of another Branch in the Current Branch.”</p><p><strong>8. Master</strong>: “ The default development Branch in Git .”</p><p><strong>9. Origin: “</strong>The default Upstream Repository.”</p><p><strong>10. Pull Requests</strong>: “Suggests changes into the Master Branch.”</p><p><strong>11. Push: “</strong>Pushes new changes after Committing them.”</p><p><strong>12. Repository: “</strong> Repository in Git is considered as your project folder. A repository has all the project-related data. Distinct projects have distinct repositories”.</p><p><strong>13. Stashing: “ </strong>It<strong> </strong>to switch branches without committing the current branch.”</p><p><strong>14. Revert</strong>: “ It is used to revert some commits.”</p><p><strong>15. Reset</strong>: “ It is used to reset the changes.”</p><p>Let us see some practically… <br>1. <strong>git clone</strong></p><pre><strong><em>git clone &lt;repository url&gt;</em></strong></pre><p><strong>2</strong>. <strong>git init<br></strong>The git init command is used to create a new blank repository. git init command creates a .git subdirectory in the current working directory.</p><pre>git init</pre><p><strong>3</strong>. <strong>git status<br></strong>The git status command is used to display the state of the repository and staging area. It allows us to see the tracked, untracked files and changes.</p><pre>git status</pre><p><strong>4</strong>. <strong>git add<br></strong>This command selects the files you updated, and that you wish to send to the remote repository.<br>To add a single file</p><pre>git add <em>&lt;</em><strong><em>file path&gt;</em></strong></pre><p>To add all the files</p><pre>git add.</pre><p><strong>5. git commit<br></strong>Once you have made some changes in the code and you saved it, you have to <strong>commit</strong> them. You are creating a little “container” of updates that you describe with a message.</p><pre>git commit -m &quot;commit message&quot;</pre><p>To add all changes to staging and commit them with a custom message.</p><pre>git commit -am &quot;commit message&quot;</pre><p><strong>6. git pull<br></strong>The term pull is used to receive data from GitHub. It fetches and merges changes from the remote server to your working directory.</p><pre>git pull &lt;branch_name&gt;</pre><p><strong>7. git push<br></strong>The term push is used to send commits to the remote branch.</p><pre>git push &lt;branch_name&gt;</pre><p><strong>8. git fetch<br></strong>With <strong>git fetch</strong> you will get the latest updates of the repository, changes in the code, and the new branches that were created.</p><pre>git fetch --all</pre><p><strong>9. git checkout<br></strong>Create a new branch to work on and switch to it.</p><pre>git checkout -b &lt;new_branch_name&gt;</pre><p>To checkout to a different branch</p><pre>git checkout &lt;branch_name&gt;</pre><p><strong>10. git stash</strong></p><pre>git stash</pre><p>If there are files that you don’t wish to commit now, you can set them aside or “stash” them. it will store all the changes, except the untracked files.</p><pre>git stash - include-untracked</pre><p>This command is used to store all the changes including untracked files.</p><pre>git stash list</pre><p>This command is used to list the stashes in the repository.</p><pre>git stash apply</pre><p>This command is used to apply a specific stash. will apply stored changes to the file.</p><pre>git stash pop</pre><p>This command is used to Apply the latest stash and removes it from the stash list.</p><p><strong>11. git revert<br></strong>You can revert the commits you created.</p><pre>git revert <strong>commitId // </strong></pre><p><strong>committed =&gt; </strong>to get the commit id do <strong>git log </strong>and will list the previous commit and select the id which you want to revert from the working branch.</p><p><strong>12. git branch<br></strong>You can also create new branches like this</p><pre>git branch &lt;new branch name&gt;</pre><p>To delete the branch locally</p><pre>git branch -d &lt;branch_name&gt;</pre><p>To delete the branch remotely</p><pre>git push &lt;remote_name&gt; --delete &lt;branch_name&gt;</pre><p><strong>13</strong>. <strong>git merge<br>Git merge</strong> is the command that “merges” or combines branches&#39; commits. Once you are done working on your branch, the last thing to do is to merge your branch with the main branch.</p><p>First, you need to be on the branch you want your branch to be merged into.</p><p><strong>Example</strong>: If you want to merge your branch <strong><em>“my-new-feature”</em></strong> into the branch called ”<strong>main</strong>”, you need to check out into <strong><em>“main”</em></strong> and run the command here.</p><p>If you don’t remember how to switch branches, type :</p><p><strong><em>git checkout main</em></strong></p><p>Before merging branches you should <strong><em>always</em></strong> fetch the latest updates:</p><p><strong><em>git fetch</em></strong></p><p>Now, you can merge your branch into the main branch :</p><p><strong><em>git merge my-new-feature.</em></strong></p><p>In conclusion, Git is a powerful version control system that allows developers to track changes to their codebase over time. Mastering essential Git commands and best practices can significantly improve your workflow and productivity as a developer. Keep exploring and experimenting with Git to find the best strategies for your projects, and remember that practice makes perfect!.</p><pre>if(youLikeMyContent){<br>   pleaseConsidrFollowingMe(😊);<br>   pleaseLikestory(😊);<br> }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b16b0335a32" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/git-commands-7b16b0335a32">Common &amp; Useful Git Commands</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced JavaScript Features]]></title>
            <link>https://blog.nonstopio.com/advanced-javascript-features-2fe8108ab4d3?source=rss-cf400c2f1da3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe8108ab4d3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <dc:creator><![CDATA[Vidya Jayagouda]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 05:51:24 GMT</pubDate>
            <atom:updated>2023-07-02T17:53:51.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Kkz2TEe7QfZk-x1li4xnyg.png" /><figcaption>Credits- Web illustrations by Storyset</figcaption></figure><p>JavaScript is one of the most dynamic languages. Each year, multiple features are added to make the language more manageable and practical.<br>Like a lot of other programming languages, JavaScript is constantly evolving. Every year, the language is made more powerful with new capabilities that let developers write more expressive and concise code.<br>Let’s explore the most recent features added in ECMAScript 2022 (ES13), and see examples of their usage to understand them better.</p><p><strong>1. Top-Level await<br></strong>Asynchronous functions were added to JavaScript in 2017. Until now, we could only use await inside the async functions. But now, the await keyword can also be used outside the async functions at the top level of a module to wait for a Promise.</p><p><strong>Before ES2022</strong></p><pre>await Promise.resolve(console.log(&#39;Hello Javascript&#39;));<br>// Output: SyntaxError: await is only valid in async function<br>// Alternative to fix the problem<br>(async function() {<br>  await Promise.resolve(console.log(&#39;Hello Javascript&#39;));<br>  // Output: Hello World<br>}());</pre><p><strong>After ES2022</strong></p><pre>await Promise.resolve(console.log(&#39;Hello Javascript&#39;));<br>//Hello Javascript</pre><p><strong>2. Class field declarations<br></strong>Before ES13, class fields could only be declared in their constructor. But now we can declare or define them in the outermost scope of the class.</p><p><strong>Before ES2022</strong></p><pre>class team{<br>  constructor() {<br>    this.teamName = &#39;Avengers&#39;;<br>    this.teamMember = 10;<br>  }<br>}<br>const oppositeTeam = new team();<br>console.log(oppositeTeam.teamName); // Avengers</pre><p><strong>After ES2022</strong></p><pre>class team {<br>  teamName = &#39;Avengers&#39;;<br>  teamMember = 10;<br>}<br>const oppositeTeam = new team();<br>console.log(oppositeTeam.teamName); // Avengers</pre><p><strong>3. Private instance fields, methods, and accessors<br></strong>Previously when was needed to declare a private method or field needs to be added an underscore _ at the beginning of the method name (based on convention), however, that does not guarantee that the method will be private.<br>With <strong>ES2022</strong> was added as new features such as private instance fields, methods, and accessors. We need to add just <strong>#</strong> at the beginning of the method name and in that way will be declared private.</p><p><strong>Before ES2022</strong></p><pre>class Person {<br>  _firstName = &#39;Merry&#39;;<br>   lastName = &#39;Smith&#39;; </pre><pre>  printPrivateField() {<br>    console.log(this.#firstName) // Merry<br>  }<br>  #sayHello() {<br>    console.log(&quot;Hello&quot;)<br>  }<br>}<br>const user = new Person();<br>// Members intended to be private can still be accessed from outside the class<br>console.log(person._firstName); // Merry<br>person._firstName = &#39;Robert&#39;; // They can also be modified</pre><p><strong>After ES2022</strong></p><pre>class Person {<br>  #firstName = &quot;Merry&quot;<br>  lastName = &quot;Smith&quot;<br><br>  printPrivateField() {<br>    console.log(this.#firstName) // Merry<br>  }<br><br>  #sayHello() {<br>    console.log(&quot;Hello&quot;)<br>  }<br>}<br>const user = new Person()<br>console.log(user.#firstName) // SyntaxError: Private field &#39;#firstName&#39; must be declared in an enclosing class<br>console.log(user.lastName) // Smith<br>user.printPrivateField() // Merry<br>user.#sayHello() // SyntaxError: Private field &#39;#sayHello&#39; must be declared in an enclosing class</pre><p><strong>4. Ergonomic brand checks for Private Fields<br></strong>This functionality helps us to check that the <em>object</em> has the given private slot in it, for this purpose, the in operator is used.</p><pre>class Person {<br> #name = &quot;Random User&quot;<br> isNamePresent () {<br>  return #name in this;<br> }<br>}<br>const user = new Person()<br>console.log(user.isNamePresent());//true</pre><p><strong>5. Static Class Fields and Static Private Methods<br></strong>We can now declare static fields and static private methods for a class in ES13. Static methods can access other private/public static members in the class using the this keyword, and instance methods can access them using this.constructor.</p><pre>class Person {<br>  static #marks = 25;<br>  static getMarks() {<br>  return this.#marks;<br>  }<br>  constructor() {<br>    this.constructor.#incrementMarks();<br>  }<br>  static #incrementMarks() {<br>    this.#marks++;<br>  }<br>}<br>const user= new Person();<br>console.log(Person.getMarks()); // 2</pre><p><strong>6.</strong><strong>at() method for </strong><strong>Strings, </strong><strong>Arrays, and </strong><strong>TypedArrays </strong><br>Until this point, programmers have asked for the ability to do <strong>negative indexing</strong> of JS Arrays, as you can do with other programming languages. That is, asking for the ability to write <strong>arr[-1]</strong> instead of <strong>arr[arr.length-1]</strong>, where negative numbers count backward from the last element.<br>This year with <strong>ES2022</strong> we have a big change with a new method that helps programmers with the <strong>negative indexing</strong>, the <strong>.at()</strong> method that is supported by <strong>Array</strong>, <strong>String</strong>, or <strong>TypedArray</strong>.</p><p><strong>Before ES2022</strong></p><pre>const array = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br>// Using the length property<br>const lastItem = array[array.length - 1]<br>console.log(lastItem) // Output: &quot;c&quot;</pre><p><strong>After ES2022</strong></p><pre>const array = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br>// Using the new at method<br>const lastElement = array.at(-1)<br>console.log(lastElement) // Output: &quot;c&quot;</pre><p><strong>7. RegExp Match Indices<br></strong>ES2022 adds a new feature to Regular Expressions called <strong>Match indices</strong>. using this we can get extra information about the start and end indices of the captured substring. To use this feature we just need to pass the/d flag in the regular expression. This feature adds indices property to the result array returned by RegExp.prototype.exec and String.prototype.matchAll methods. The indices property is an array that contains the start and end indices of each matched substring relative to the starting of the input.</p><p><strong>Before ES2022</strong></p><pre>const str = &quot;welcome to welcome&quot;<br>// without /d flag<br>const regex = /(welcome)/g<br>console.log(...str.matchAll(regex));<br>//output<br>[<br>  &#39;welcome&#39;,<br>  &#39;welcome&#39;,<br>  index: 0,<br>  input: &#39;welcome to welcome&#39;,<br>  groups: undefined<br>]</pre><p><strong>After ES2022</strong></p><pre>const str = &quot;welcome to welcome&quot;<br>// without /d flag<br>const regex = /(welcome)/dg<br>console.log(...str.matchAll(regex));<br>//output<br>[<br>  &#39;welcome&#39;,<br>  &#39;welcome&#39;,<br>  index: 0,<br>  input: &#39;welcome to welcome&#39;,<br>  groups: undefined,<br>  indices: [ [ 0, 7 ], [ 0, 7 ], groups: undefined ]<br>]</pre><p><strong>8. Object.hasOwn()<br></strong>In JavaScript we already have an Object.prototype.hasOwnProperty but it’s best to not use hasOwnProperty outside the prototype itself as it is not a protected property, meaning that an object could have its property called hasOwnProperty</p><p><strong>Before ES2022</strong></p><pre>const object = {<br> name: &quot;Draxlr&quot;,<br> hasOwnProperty (){<br>  return false<br> }<br>}<br>console.log(object.hasOwnProperty(&quot;name&quot;)); // false<br>console.log(object.hasOwnProperty(&quot;hasOwnProperty&quot;)); // false</pre><p><strong>After ES2022</strong></p><pre>const user = {<br> name: &quot;JavaScript&quot;,<br> hasOwnProperty() {<br>   return false;<br> },<br>}<br>console.log(Object.hasOwn(user, &quot;name&quot;)); // Output: true<br>console.log(Object.hasOwn(user, &quot;hasOwnProperty&quot;)); // Output: true</pre><p><strong>9. Error Cause<br>Error</strong> and its <strong>subclasses</strong> now let us specify the reason behind the error. Sometimes, we catch errors that are thrown during more deeply nested function calls and would like to attach more information to them.<br>With the <strong>Error cause</strong>, we can add more intrinsic information for our errors. To use this new feature, we should specify the error options as a second parameter, and with the <strong>cause</strong> key we can pass the error that we want to chain.</p><pre>const getUsers = async(array)=&gt; {<br>try {<br>  const users =  await fetch(&#39;https://myapi/myusersfake&#39;);<br>  return users;<br>}<br>catch (error) {<br>  console.log(&#39;enter&#39;);<br>  throw new Error(&#39;Something when wrong, please try again later&#39;, <br>  {cause: error });<br>}<br>}<br>try{<br>  const users = await getUsers();<br>} <br>catch(error) {<br>  console.log(error); <br>  // Error: The array need a minimum of two   elements<br>  console.log(error.cause); // TypeError: Failed to fetch<br>}</pre><p><strong>10. Array Find from Last<br></strong>In JavaScript we already have an Array.prototype.find and Array.prototype.findIndex. We know how to find from last may have better performance (The target element on the tail of the array, could append with push or concat in a queue or stack, <strong>eg</strong>: recently matched time point in a timeline). If we care about the order of the elements (May have a duplicate item in the array, <strong>eg</strong>: last odd in the list of numbers), a better way to use <em>new methods</em> Array.prototype.findLast and Array.prototype.findLastIndex.</p><p><strong>Before ES2022</strong></p><pre>const array1 = [5, 12, 8, 130, 44];<br>const found = array1.find(element =&gt; element &gt; 10);<br>const isLargeNumber = (element) =&gt; element &gt; 10;<br>console.log(found);//12<br>console.log(array1.findIndex(isLargeNumber));//1</pre><p><strong>After</strong> <strong>ES2022</strong></p><pre>const array1 = [5, 12, 8, 130, 44];<br>const found = array1.findLast(element =&gt; element &gt; 10);<br>const isLargeNumber = (element) =&gt; element &gt; 10;<br>console.log(found);//44<br>console.log(array1.findLastIndex(isLargeNumber));//4</pre><h3>Conclusion</h3><p>So we have learned the latest features ES2022 brings to JavaScript. Use them to improve your code efficiency and boost your productivity as a developer and write cleaner code with greater conciseness and clarity.</p><p>— — —</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@vidya.jayagouda"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe8108ab4d3" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/advanced-javascript-features-2fe8108ab4d3">Advanced JavaScript Features</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>