<?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: SREY</title>
    <description>The latest articles on DEV Community by SREY (@delisrey).</description>
    <link>https://dev.to/delisrey</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%2F609190%2F5d04a7a6-5e15-4b55-82be-55c2a092307a.jpg</url>
      <title>DEV Community: SREY</title>
      <link>https://dev.to/delisrey</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/delisrey"/>
    <language>en</language>
    <item>
      <title>Rendering One Million Checkboxes Efficiently: Performance Insights using Vanilla JS🙃</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Sun, 08 Sep 2024 11:21:14 +0000</pubDate>
      <link>https://dev.to/delisrey/rendering-one-million-checkboxes-efficiently-performance-insights-using-vanilla-js-5eoe</link>
      <guid>https://dev.to/delisrey/rendering-one-million-checkboxes-efficiently-performance-insights-using-vanilla-js-5eoe</guid>
      <description>&lt;p&gt;Hello Beautiful People of the Internet! 🚀&lt;/p&gt;

&lt;p&gt;I've been on a rollercoaster journey these past few months, building the MVP of my product, &lt;strong&gt;&lt;a href="https://talez-flames.vercel.app/" rel="noopener noreferrer"&gt;Talez&lt;/a&gt;&lt;/strong&gt;. Amidst all the ups and downs, something cool caught my eye: the viral "One Million Checkbox" challenge that's been buzzing online. But there's more to this chaos than just a sea of checkboxes—it’s a fascinating dive into performance optimization and scalability.&lt;/p&gt;

&lt;p&gt;I'll link to the original blog at the end so you can see how the author scaled their system for a million users. But for now, I was curious about how One Million Checkboxes would actually behave. I knew there was no way they would render smoothly without some help from those fancy tech terms... wait, what were they called again? (Pausing for effect)… Ah yes, Lazy Loading!&lt;/p&gt;

&lt;p&gt;Let's dig into the madness and figure out how we can handle this ocean of checkboxes without losing our sanity—or our app’s performance!&lt;/p&gt;

&lt;h3&gt;
  
  
  Figuring it Out 🤔:
&lt;/h3&gt;

&lt;p&gt;The first challenge was to figure out how to render thousands of checkboxes without crashing the browser or breaking the code. I knew about concepts like lazy loading and batch rendering, but I soon realized those alone wouldn’t be enough. As seen on &lt;a href="https://onemillioncheckboxes.com/" rel="noopener noreferrer"&gt;One Million Checkbox&lt;/a&gt;, the checkboxes render on scroll, leveraging the viewport of the DOM —meaning only the checkboxes visible in the view are rendered.&lt;/p&gt;

&lt;p&gt;A bit of research led me to the IntersectionObserver API in JavaScript. This API allows us to observe elements as they enter or exit the viewport, making it perfect for implementing lazy loading of checkboxes. By rendering only the checkboxes that come into view, we can manage performance efficiently and avoid overwhelming the browser.&lt;/p&gt;

&lt;h4&gt;
  
  
  💡Note :
&lt;/h4&gt;

&lt;p&gt;The original site may have a little different implementation. I might try and explore different way to render checkbox UI using vanila JS, in current implementation of &lt;a href="https://onemillioncheckboxes.com/" rel="noopener noreferrer"&gt;One Million Checkbox&lt;/a&gt; there is a way where only selected amount of checkboxes are rendered inside the view port if i remember correctly it is called windowing or virtualization.&lt;/p&gt;

&lt;h3&gt;
  
  
  Building Blocks in JS for rendering UI Checkboxes:
&lt;/h3&gt;

&lt;p&gt;Let's start by setting up the basic structure using HTML. We don’t need much code here—just a simple layout to get things started. I’ve also added some CSS styles to improve the overall appearance: padding inside the &lt;/p&gt; for better spacing, gaps between the checkboxes for a cleaner look, and a flex-wrap property to ensure the checkboxes stack neatly across multiple lines. 

&lt;p&gt;Ahoy This is all we need from out HTML code !&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;One Million Checkboxes&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }

        #checkbox-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            /* Space between each checkbox */
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
    &amp;lt;div id="checkbox-container"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

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

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;"Let’s spice up the basic structure with some Vanilla JavaScript (no pun intended!)."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As discussed earlier, we'll be leveraging the IntersectionObserver API, but before diving into it, we need to address potential rendering issues that might arise with such a large number of elements. To handle this efficiently, we'll implement batch rendering of checkboxes. This approach allows us to render checkboxes in manageable batches, gradually building up to our target of one million checkboxes without overwhelming the browser.&lt;/p&gt;

&lt;p&gt;1.) Let's start with some dom manipulation's and some declaring global variables first&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const container = document.getElementById("checkbox-container");

const checkboxCount = 1000000; // total number of checkboxes we need to render
const batchSize = 1000; // Number of checkboxes to render at once
let lastRenderedIndex = 0; // track for us when we use observer api 

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

&lt;/div&gt;

&lt;p&gt;The last rendered index refers to the position of the last checkbox that was rendered within the current viewport. As we scroll, we'll dynamically add a new batch of checkboxes based on this index, incrementally increasing the rendered count. We’ll use the IntersectionObserver API to unobserve the previously rendered elements and observe the latest ones.&lt;/p&gt;

&lt;p&gt;2.) Now lets implement the batch-rendering function &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function createCheckboxesBatch(startIndex, endIndex) {
  const fragment = document.createDocumentFragment();

  for (let i = startIndex; i &amp;lt; endIndex; i++) {
    const checkboxItem = document.createElement("div");
    checkboxItem.className = "checkbox-item";

    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = `checkbox-${i}`;
    checkbox.name = `checkbox-${i}`;

    checkboxItem.appendChild(checkbox);
    fragment.appendChild(checkboxItem);
  }

  container.appendChild(fragment);
}


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

&lt;/div&gt;

&lt;p&gt;Here I have added the checkboxes batch function named &lt;code&gt;createCheckboxesBatch&lt;/code&gt; which takes &lt;code&gt;startIndex&lt;/code&gt; and an &lt;code&gt;endIndex&lt;/code&gt; and inside the func we create a fragment from the document &lt;/p&gt;

&lt;p&gt;Within the &lt;code&gt;#checkbox-container&lt;/code&gt; div, we start by creating an input element for each checkbox. We set the type attribute to "checkbox" to define it as a checkbox input. Additionally, we assign each checkbox a unique id and name based on its current index number. This approach helps in debugging by making it easy to identify each checkbox by its corresponding index.&lt;/p&gt;

&lt;p&gt;and then now we append the checkbox to the checkboxItem to checkbox and than assigning the fragment to the container.&lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Are you thinking wth createDocumentFragment does in JS DOM&lt;/em&gt;?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We create a new empty DocumentFragment, which allows us to build an offscreen DOM tree where DOM nodes can be added without affecting the main document. This fragment is not part of the actual DOM until it's appended, at which point it is replaced by all its child nodes in the DOM tree. This approach improves performance by minimizing reflows and repaints. For more details, you can check the documentation on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment" rel="noopener noreferrer"&gt;MDN&lt;/a&gt;.&lt;/p&gt;

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

&lt;p&gt;3.) But let move forward where we can actually write the next set of code lines where we write a function checking do we need to load more checkboxes and if yes we ideally change the &lt;code&gt;lastRenderedIndex&lt;/code&gt; with the batchSize.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function loadMoreCheckboxes() {
  if (lastRenderedIndex &amp;lt; checkboxCount) {
    createCheckboxesBatch(
      lastRenderedIndex,
      Math.min(lastRenderedIndex + batchSize, checkboxCount)
    );
    lastRenderedIndex += batchSize;
  }
}

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

&lt;/div&gt;

&lt;p&gt;4.) Now we shall add the Observer API logic which we intend to implement before &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const observer = new IntersectionObserver(
  (entries) =&amp;gt; {
    entries.forEach((entry) =&amp;gt; {
      if (entry.isIntersecting) {
        loadMoreCheckboxes();
        observer.unobserve(entry.target);
        // Observe the last child again after loading more checkboxes
        if (lastRenderedIndex &amp;lt; checkboxCount) {
          observer.observe(container.lastElementChild);
        }
      }
    });
  },
  {
    rootMargin: "100px", // Load more checkboxes just before reaching the end of the container
  }
);

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

&lt;/div&gt;

&lt;p&gt;The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Break Down :/&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;👺 Creating the IntersectionObserver:&lt;/p&gt;

&lt;p&gt;We start by creating an &lt;code&gt;IntersectionObserver&lt;/code&gt; instance, passing it a callback function that runs whenever observed elements enter or exit the viewport. The callback function receives a list of &lt;code&gt;entries&lt;/code&gt;, which represent the observed elements and their intersection status with the viewport.&lt;/p&gt;

&lt;p&gt;👺 Processing Each Entry:&lt;/p&gt;

&lt;p&gt;For each entry in entries, we check if it is intersecting (i.e., visible within the specified viewport). If &lt;code&gt;entry.isIntersecting&lt;/code&gt; is true, it means the element is in view or close enough based on the root margin.&lt;br&gt;
When an entry intersects, we call &lt;code&gt;loadMoreCheckboxes()&lt;/code&gt;, a function implemented to add a new batch of checkboxes to our container.&lt;/p&gt;

&lt;p&gt;👺 Managing Observations:&lt;/p&gt;

&lt;p&gt;After loading more checkboxes, we use &lt;code&gt;observer.unobserve(entry.target)&lt;/code&gt; to stop observing the current entry, which prevents repeated calls as the user continues scrolling.&lt;/p&gt;

&lt;p&gt;To keep the process going, we then observe the last newly added checkbox using &lt;code&gt;observer.observe(container.lastElementChild)&lt;/code&gt;. This step ensures that as soon as the last checkbox in the current batch comes into view, more checkboxes are loaded, creating a seamless user experience.&lt;/p&gt;

&lt;p&gt;👺 Root Margin:&lt;/p&gt;

&lt;p&gt;The observer is configured with a rootMargin of "100px", which acts as a buffer zone around the viewport. This means the observer will trigger loadMoreCheckboxes() 100 pixels before the target element actually enters the viewport, ensuring that new checkboxes are loaded just in time to avoid any visible gaps or delays in rendering.&lt;/p&gt;

&lt;p&gt;And lastly add the function for observing the last child when the user lands on the page for the first time ever and we start observing lastElement by &lt;code&gt;observer.observe(container.lastElementChild)&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Start by observing the last child
createCheckboxesBatch(0, batchSize);
lastRenderedIndex += batchSize;
observer.observe(container.lastElementChild);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I have curated a JAM link where I added a console with the last rendered index here is the link &lt;a href="https://jam.dev/c/623545b7-000b-4318-85bb-4064a723c8d2" rel="noopener noreferrer"&gt;https://jam.dev/c/623545b7-000b-4318-85bb-4064a723c8d2&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So let us run throught the intrusive thoughts of performance with the contributor who used virtual DOM versus when we used IntersectionObserver API.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Windowing, Efficiently renders only the visible portion of large lists, reducing the number of DOM elements and improving performance significantly. Ideal for uniform lists where the size of items is predictable, like tables or grids. But it does Struggles with dynamic or varying content heights, requiring additional logic to handle discrepancies. Less suited for complex interactions or elements outside of simple scrollable views.&lt;/p&gt;

&lt;p&gt;In contrast, the IntersectionObserver API offers superior performance for large datasets by rendering only visible elements, thus reducing memory usage and enhancing responsiveness with on-demand loading. However, it is less effective for handling frequent updates or complex interactions.&lt;/p&gt;

&lt;p&gt;Here is the blog to the original author's blogpost:&lt;br&gt;
&lt;a href="https://eieio.games/nonsense/game-14-one-million-checkboxes/" rel="noopener noreferrer"&gt;https://eieio.games/nonsense/game-14-one-million-checkboxes/&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Thank you for reading. It’s been great exploring these concepts with Vanilla JS. If you like the post drop a like and a comment if you have new way to add these one million checkbox on the UI screen. See you in the next post!&lt;/p&gt;

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

</description>
      <category>ui</category>
      <category>performance</category>
      <category>frontend</category>
      <category>frontendchallenge</category>
    </item>
    <item>
      <title>Infinite list loading 🤔, with React Query - useInfiniteQuery hook !</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Tue, 09 Jul 2024 03:18:11 +0000</pubDate>
      <link>https://dev.to/delisrey/infinite-list-loading-with-react-query-useinfinitequery-hook--19i</link>
      <guid>https://dev.to/delisrey/infinite-list-loading-with-react-query-useinfinitequery-hook--19i</guid>
      <description>&lt;p&gt;Sometimes getting all the data in a single API query is worth than getting it in the form of paginated data, but not in every case what if you need the API to be more optimized and efficient hence implementing a infinite loading kind of a feature from scratch might not only be complicated but also overwhelming if you are just a beginner in React, Let's see how react-query makes it possible with the help of infinite queries.&lt;/p&gt;

&lt;p&gt;Hello I am &lt;a href="https://x.com/shreykoradia" rel="noopener noreferrer"&gt;SHREY&lt;/a&gt;, your author and the guide to put you up on a step closer on mastering react-query with implementing infinite loading list feature from scratch with the help of react-query.&lt;/p&gt;

&lt;p&gt;So now if we see, for example real world application like &lt;a href="https://dribbble.com/" rel="noopener noreferrer"&gt;Dribble &lt;/a&gt;, we may find a &lt;code&gt;Browse More Inspiration&lt;/code&gt; kind of a button at the bottom of the screen after some amount of web mockups are displayed, so on clicking that button we may find more amount of data displayed again and the cycle continues.&lt;/p&gt;

&lt;p&gt;So one way is we give a button and on the click of it we may find a set of data thrown at the client from the server or otherwise we could make the use of infinite queries with the help of scroll in that case we may need to use &lt;a href="https://www.npmjs.com/package/react-intersection-observer" rel="noopener noreferrer"&gt;react-intersection-observer&lt;/a&gt; to get new data based on the viewport and scroll trigger.&lt;/p&gt;

&lt;p&gt;Lets build the feature with a button saying load more data, without furthure ado 😅.&lt;/p&gt;

&lt;p&gt;So Let us define how we could get the data from the backend, for example different api handles pagination differently, in my case I have limit and offset kind of a thing where developer from frontend handles limit of data they want with the help of offset, so my response structure from backend would be somewhat like the below example stated:&lt;/p&gt;

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

{
  "feedbacks": {
    "totalPages": 1,
    "feedbacks": [
      {
        "_id": "6624d529440d8153b9967515",
        "feedback": "Hehe cool think to do",
        "feedback_author_id": "6621e2621755214cca2e300b",
        "feedback_author_name": "test1",
        "tale_id": "65f6bbd6feec14b3e8804846",
        "created_at": "2024-04-21T08:58:17.963Z",
        "__v": 0
      },
      {
        "_id": "662afb1caca2a90e470bc78f",
        "feedback": "sddsdsdd",
        "feedback_author_id": "65b38594f8211ed0962fe067",
        "feedback_author_name": "shrey",
        "tale_id": "65f6bbd6feec14b3e8804846",
        "created_at": "2024-04-26T00:53:48.653Z",
        "__v": 0
      },
      {
        "_id": "662afb34aca2a90e470bc79c",
        "feedback": "xoxo",
        "feedback_author_id": "65b38594f8211ed0962fe067",
        "feedback_author_name": "shrey",
        "tale_id": "65f6bbd6feec14b3e8804846",
        "created_at": "2024-04-26T00:54:12.671Z",
        "__v": 0
      }
    ]
  }
}



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

&lt;/div&gt;

&lt;p&gt;Now I will be having a backend api endpoint in somewhat this fashion where user can attach limit and offset in the form of query params&lt;/p&gt;

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

http://localhost:3000/v1/feedback/get-feedbacks?taleId=123&amp;amp;offset=12&amp;amp;limit=6


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

&lt;/div&gt;

&lt;p&gt;Okay so my only point of stating this was to get easily think how our hasNextPage params work in frontend when we try to apply it using inifite queries. &lt;/p&gt;

&lt;p&gt;lets see how we need to handle react-query hook called &lt;code&gt;useInfiniteQuery&lt;/code&gt;&lt;/p&gt;

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

 const fetchFeedbacks = ({ pageParam = 0 }) =&amp;gt; {
    return getFeedbacks({ taleId: params.taleId, offset: pageParam });
  };

 const query = useInfiniteQuery({
    queryKey: ["get-feedbacks", params?.taleId],
    queryFn: fetchFeedbacks,
    initialPageParam: 0,
    getNextPageParam: (lastPage, lastPageParam) =&amp;gt; {
      if (lastPage.data.feedbacks.feedbacks.length === 0) {
        return undefined;
      }
      return lastPageParam.length * LIMIT;
    },
    enabled: !!params?.taleId,
  });



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

&lt;/div&gt;

&lt;p&gt;In this above piece of code we have assigned our values returning from the useInfinteQuery to a variable where we already have known in our previous blogs about the queryKey , queryFn etc but here we see &lt;code&gt;initalPageParam&lt;/code&gt;, this is a parameter required by default when using this hook which helps in fetching the first page we set it to 0 and hence this will get us the first page data from the backend server. Hence when the api endpoints get fired the offset in the api endpoint tends to be 0 and the data actually is fetch from the 0th index or in layman terms we say page.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;getNextPageParam&lt;/code&gt; is a callable function which return a single variable in the docs it is described something like this:&lt;/p&gt;

&lt;p&gt;When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. &lt;/p&gt;

&lt;p&gt;so how did I used getNextPageParam is similar to what written above, this means lastPage with the data returned by the API endpoint *&lt;em&gt;if having length === 0 than I will return undefined stating that there is no more data that can be sent back to client from the server *&lt;/em&gt; otherwise I will be returning the next page param which will get us the data from the backend server  lastPageParam.length * LIMIT, I have also added how I would get the lastPageParam and what I will be returning , offset is what will be returned by &lt;code&gt;lastPageParam.length * LIMIT&lt;/code&gt;.&lt;/p&gt;

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

&lt;p&gt;and you already know what enabled is and how do we already use it and why we use it. If you are not familiar to the enabled keyword you know the drill =&amp;gt; get to my previous &lt;a href="https://dev.to/delisrey/series/24656"&gt;blogs &lt;/a&gt;and dig the docs to find out what enabled does.&lt;/p&gt;

&lt;p&gt;There are also other set of parameter where you could use it with useInfiniteQuery such as getPreviousPageParam and maxPages you could dig a deeper view it on the react-query docs but getPreviousPages does the similar thing as getNextPageParams but it takes &lt;code&gt;firstPage, allPages, firstPageParam, allPageParams&lt;/code&gt; firstPage and firstPage params while maxPages is the number of pages to be stored in the infinite query data.&lt;/p&gt;

&lt;p&gt;This is how it will display it, I have recorded a prime use case from one of my product that i am gonna make it enable to use for the new users for &lt;br&gt;
brainstorming and creating story boards for the application soon.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://jam.dev/c/0b3c18fd-d250-4bc5-96fb-69d01ce7f915" rel="noopener noreferrer"&gt;https://jam.dev/c/0b3c18fd-d250-4bc5-96fb-69d01ce7f915&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This was all for now, I know I am not curating a blog every week like the way I used to curate before, but I will try my best. Also lets not forget to like and share the blog with others and comment any good or optimized way to handle the react query  useInfiniteQuery hook I would love to know your feedbacks as well, &lt;/p&gt;

&lt;p&gt;btw Hello once again I am SHREY, Part-time SDE at Talez (hacking on my product) otherwise I do a full time Software Development at an early scale start-up if you reached till here reading the blog do follow me and yeah have a happy working week Bye:)&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>SQL Querying Made Simple with GraphQL and Prisma !</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 01 Apr 2024 05:48:11 +0000</pubDate>
      <link>https://dev.to/delisrey/sql-querying-made-simple-with-graphql-and-prisma--163i</link>
      <guid>https://dev.to/delisrey/sql-querying-made-simple-with-graphql-and-prisma--163i</guid>
      <description>&lt;h3&gt;
  
  
  Hola Amigos
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;In todays blog we will see how we can built a sql querying mechanism using prisma and graphQL , We will be using GraphQL using the Apollo Client and a graphQL server inference using  express.&lt;/p&gt;

&lt;p&gt;Tech stacks used here are :&lt;br&gt;
GraphQL , Prisma PgSql dump , Express (inferencing the GraphQL backend Server).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you want your graphQL queries, communicating with our backend interface we just might need to do something I am doing below in React this is just a configuration part which I would like to show technically, that how could we configure graphQL on the frontend part.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const client = new ApolloClient({
  uri: import.meta.env.VITE_APP_GRAPHQL_API,
  cache: new InMemoryCache(),
});

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

&lt;/div&gt;



&lt;p&gt;Then we will use it like this wrapping up the App Component as we will be using the client across the whole application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;ApolloProvider client={client}&amp;gt;
  &amp;lt;App /&amp;gt;
 &amp;lt;/ApolloProvider&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;The above code have to be written inside the main.tsx file or inside the index.ts file if using cra , where the root is render inside the ReactDom. The above code creates the client , with the help of apollo-client library use to create a client for using GraphQL it takes two parameters the uri which is nothing but the backend inference of the GraphQL API and a cache parameter where we have defined InMemoryCache() where the apollo client responds immediately if have stored the queries inside the local cache storage without the network request.&lt;/p&gt;

&lt;p&gt;Now we need to Focus towards the Express where we will be inferencing the GraphQL server for mutating and fetching the data from our post-gres data dump&lt;/p&gt;

&lt;h3&gt;
  
  
  Lets start with the Setup in backend for GraphQL followed by Prisma
&lt;/h3&gt;

&lt;p&gt;Here we don't see much of the configuration to be set up but only the Apollo Server to serve the client request, our main focus here would be to make resolver function and schema files accurately and precisely as it may be quite messy sometimes when the product code base get's quite huge.&lt;/p&gt;

&lt;p&gt;in my &lt;code&gt;./index.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const server = new ApolloServer({
  schema,                        // you executable schema file
  context: ({ req }) =&amp;gt; ({
    db,                         // your database connection
  }),
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

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

&lt;/div&gt;



&lt;p&gt;In my case I am using Postgres Databse Dump so I will be using  pg-promise to make a database instance and make a connection string.Also I have attached how we will be using it from .env file as if some newbie reads the blog they might get a sense how a production / industry application needs to developed 🗿.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pgp = pgPromise();
export const db = pgp({
  connectionString: `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}`,
});

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

&lt;/div&gt;



&lt;p&gt;Now Lets get towards the executable schema files and give it to apollo server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import makeExecutableSchema from "graphql-tools" // also add it into the file

const schema = makeExecutableSchema({ typeDefs, resolvers });

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  So what are typeDef and resolvers ?
&lt;/h3&gt;

&lt;p&gt;TypeDefs are nothing but a schema file where the datatype of the field mentioned, something similar to the types in typescript , I will add some of it how do we mentioned in the file and also some scalar types how do we manage some scalar types and how do we create some custom typedef using GraphQLScalarTypes. Also linking a document from &lt;a href="https://www.apollographql.com/docs/apollo-server/schema/schema/" rel="noopener noreferrer"&gt;ApolloGraphQL&lt;/a&gt; for making schema more better and sound.&lt;/p&gt;

&lt;p&gt;also in my &lt;code&gt;./schema.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let us assume I am making something like &lt;code&gt;user_secrets&lt;/code&gt; having my DB entites in following manner&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; type sus_users_talez{
        id: Int!,
        created_at: TimestampWithTimezone!,
        updated_at: TimestampWithTimezone,
        deleted_at: TimestampWithTimezone,
        name: String,
        sus_created_at: TimestampWithTimezone,
        sus_updated_at: TimestampWithTimezone,
        visibility: String,
        workflows: [String],

    }

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

&lt;/div&gt;



&lt;p&gt;Here you can see I have TimeStampWithTimeZone which is a custom typeDef, we will create this in a miniute&lt;/p&gt;

&lt;p&gt;But before that , I want to show how will we make a Schema File more good the above was just an example of type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const typeDefs = `#graphql
    scalar TimestampWithTimezone
    scalar JSON

 type sus_users_talez{
        id: Int!,
        created_at: TimestampWithTimezone!,
        updated_at: TimestampWithTimezone,
        deleted_at: TimestampWithTimezone,
        name: String,
        sus_created_at: TimestampWithTimezone,
        sus_updated_at: TimestampWithTimezone,
        visibility: String,
        workflows: [String],


    }


// this typedef will be responsible for Querying (Remember useQuery in ApolloGraphQL for fetching data from server)

// Note : I have also shown how it will take parameter for Pagination and a id for specifc user data. 

type Query {

 # Query to get all sus_users_talez
  getAllSusUsers(limit:Int, offset:Int): [sus_users_talez]

 # Query to get sus_users_talez by ID
  getSusUser(id: Int!): sus_users_talez

}

// Similarly we will create a Mutation typedef to accomplish Querying from frontend.

 type Mutation {
        # mutation endpoint for customSQL queries from frontend
        customSQLQuery(limit:Int, offset: Int, sql: String! , user_id: String!): JSON

}`

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

&lt;/div&gt;



&lt;p&gt;Also let me get back to the Custom Scalar type :) , And we will just add it to the above type we exported, in the same file or create and export it from a new file.&lt;/p&gt;

&lt;p&gt;Also to note GraphQL supports JSON by itself, above in mutation we have used it as user from frontend will send a JSON formatted payload.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { GraphQLScalarType } from "graphql";


export const TimestampWithTimezone = new GraphQLScalarType({
  name: "TimestampWithTimezone",
  description: "Timestamp with timezone offset",
  serialize: (value) =&amp;gt; {
    // Serialize a timestamp value from your database
    return value.toISOString();
  },
  parseValue: (value) =&amp;gt; {
    // Parse a timestamp value from a client input
    return new Date(value);
  },
  parseLiteral: (ast) =&amp;gt; {
    if (ast.kind === Kind.STRING) {
      // Parse a timestamp from an AST literal
      return new Date(ast.value);
    }
    return null;
  },
});

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

&lt;/div&gt;



&lt;h4&gt;
  
  
  Next up is Resolver Function, how we will create a Resolver Function which returns the data on the basis of User Request from Client.
&lt;/h4&gt;

&lt;p&gt;Let us start building our resover file from scratch :)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const resolvers = {
  Query: {
    getAllSusUsersTalez: async (parent, { limit, offset }) =&amp;gt; {
      try {
        // Use Prisma to fetch all sus_users_talez
        const allUsers = await prisma.sus_users_talez.findMany({
          skip: offset,
          take: limit,
        });
        return allUsers;
      } catch (error) {
        console.error("Error fetching sus_users_talez:", error);
        throw error;
      }
    },
}

 Mutation: {
    customSQLQuery: async (parent, { limit, offset, sql, user_id }) =&amp;gt; {
      try {
        // handling the recent queries
        // fetching the user_details for the metaData
        const user = await prisma.talez.findUnique({
          where: {
            user_id: user_id,
          },
        });

        // keeping a track for complete data count without offset
        const countQuery = `SELECT COUNT(*) FROM (${sql}) AS total`;
        const totalCount = await prisma.$queryRawUnsafe(countQuery);


        const paginatedSQL = `${sql} LIMIT ${limit} OFFSET ${offset}`;
        const result = await prisma.$queryRawUnsafe(paginatedSQL);

        // Check if there are more items
        const hasMoreItems = offset + limit &amp;lt; totalCount[0]?.count;

        return { result: result, hasMoreItems };
      } catch (error) {
        console.error("Error executing SQL query:", error);
        return { message: "Error Executing SQL Query, Try Different Query" };
      }
    },
  }

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

&lt;/div&gt;



&lt;p&gt;Here I have created a query function where I have tried fetching all the data related to the sus_users_talez also I have a added a mutation function where users can easily write a custom sql query if they want something by LIMIT and offset also they can easily get that. &lt;/p&gt;

&lt;p&gt;For example &lt;code&gt;Select * From sus_users_talez  WHERE id="12345"&lt;/code&gt; and kaboom you get your result's.&lt;/p&gt;

&lt;p&gt;PS: Building on top of prisma would make some extra efforts like prisma schema files and migrations if you alter any fields, if you have already a DB dump like me you will need to have a db pull with all the schema related stuff and you just need to hit a command called &lt;code&gt;prisma db pull&lt;/code&gt; you can find it to the docs of &lt;a href="https://www.prisma.io/docs/orm/reference/prisma-cli-reference" rel="noopener noreferrer"&gt;prisma&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So now you might create many more reference from here using graphQL more adequately and also making a better use case of application you want to built on the top of GraphQL, Prisma and PG-sql using express and any Frontend framework.&lt;/p&gt;

&lt;p&gt;Btw, I have never given my introduction on my past blogs , Here Find me out Who I am? :)&lt;/p&gt;

&lt;p&gt;I am &lt;a href="//www.github.com/shreykoradia"&gt;SHREY&lt;/a&gt;, SDE at early scale startup building a asset managment and compliance based application also helping people make MVP's of their startup application, I am also building &lt;a href="https://twitter.com/hello_talez" rel="noopener noreferrer"&gt;Talez&lt;/a&gt; a product management tool where you can brainstorm the ideas of the application while building your product with many others working on the same.&lt;br&gt;
You can follow me on &lt;a href="//www.twitter.com/shreykoradia"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Share it for good karma &amp;amp; 🍧 ! , Have a Great Day Folks!&lt;/p&gt;

</description>
      <category>react</category>
      <category>programming</category>
      <category>graphql</category>
      <category>prisma</category>
    </item>
    <item>
      <title>Product That I could never Publish, Unveiling Lessons from my failed attempts✨</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 04 Mar 2024 06:57:43 +0000</pubDate>
      <link>https://dev.to/delisrey/product-that-i-could-never-publish-unveiling-lessons-from-my-failed-attempts-5ena</link>
      <guid>https://dev.to/delisrey/product-that-i-could-never-publish-unveiling-lessons-from-my-failed-attempts-5ena</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Hello Beautiful People of the Internet, Welcome to my blog once again, Today I have got no series to be continued or any specific tech blog but this is one of the blog where I think people like me need to avoid this mistakes once they step into building a product which could be huge in the market and that targets the specific audience or niche category. So have a Cup of Coffee for all those who are reading before coding or grab a fruit who are already on a break reading this while coding, Here I unveil my mistakes while building a product from scratch.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's unveil the lessons without further ado!&lt;/p&gt;

&lt;h2&gt;
  
  
  Lesson One - Get a Better Product Market fit check :
&lt;/h2&gt;

&lt;p&gt;While working on my first idea I took a lot of jab at people on validating my idea and this led me to not so great path and indeed that lead me to indirectly kill my product in five to six months, while it was in the development phase.&lt;/p&gt;

&lt;h3&gt;
  
  
  Idea Reveal :)
&lt;/h3&gt;

&lt;p&gt;Any how the above will only justify when I tell you the complete story, In last Feb before I decided that I would pursue a full time job at SDE-1 position. I was thinking of building something from scratch right when I joined my University I was keen at building things got into multiple hackathon's, also the SIH'22 (Smart India Hackathon) which I made a decent positioning of Finalist making some great product for Problem Statement provided by Ministry Of Education. But this all never lasted long enough till I graduated from University, I wanted to build something huge which got some potential revolutionising the industry, For me it was my favourite one, the industry of anime and Manga though I was not an avid reader of Manga but I loved to read and binge watch some anime lately. Although it was not any streaming application. It was something related to people posting there cosplay and anime dressed photos and videos on our application which could help Manga Artist to get there anime character images in just a click and help themselves saving a lot of time and effort to draw some side characters of there recent manga and stuff though it could also help people make some random anime as well by using these characters, But underlying my social media application I thought of these AI/ML stuff and a market place idea which I thought with some friend of mine while getting use cases for this idea. I almost took some time after Feb which got me started developing it and all other check's done we started developing at the end of the Month of June. I thought to keep that stuff open-source for a while but not really later on.&lt;/p&gt;

&lt;p&gt;But later on Coming on the Above Point I wrote Get a Better Product Market Check, I and my friend who was at same University whom I guess had some basics about Machine Learning while he was learning it, where in some search about the people who could validate our idea met some of the people who couldn't stop asking us what's the purpose of building things related to anime , I guess I heard hundreds of time the same thing that India doesn't have a market around it to support the same but I wasn't developing some stuff for money or instead we could say, I was in search, If I could make a product which could result us some yield by the market place model, but the stuff people took more seriously was the Business Model of the Application, While I thought of creating Algorithms and Own Models for the Anime Characters on the Underlying Principles of Stable Diffusion. But I I always thought all my products from the perspective of Engineering's mindset that this could be built and scaled like this rather than going hard on business side of it. Also Where I lived doesn't have a tech culture as India's Silicon valley So People Never Understood this part that experimenting a product is a stuff which could help people like me understand how does this dynamics work for a betterment of application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Lesson Two - Get Good People With Who you built the product :
&lt;/h3&gt;

&lt;p&gt;I had three or four university friends through out the four year programme from which I told two of them my idea to work on they agreed but not really as we decided to go ahead we remained (sorry cut the we) I remained (who could develop practically) two of the one was the above friend with whom I got my idea converted to some use-cases and the other one was similarly planning to do something huge for portfolio's same as me and the other lad, But with Zero Motivation and this all drained in few months remaining only with two people with one who was still learning. And hence I thought product building was tough when especially you only got the addiction of building big but you can't keep people motivated with no incentives / (pretty cool word) &lt;code&gt;bucks&lt;/code&gt;.   &lt;/p&gt;

&lt;h3&gt;
  
  
  Lesson Three - Friends With Job, Makes the Product Enemy:
&lt;/h3&gt;

&lt;p&gt;While All this mess I already had a job which is still I am currently pursuing, but this was to only fuel some of the costs that could be paid for my side project as I recently graduated so I didn't wanted bigger bills to be paid by my parents hence I thought it was a great decision to go two timing building my product at night (two-three hours I mean) and doing a full time job together which absolutely make sense but for a bigger product and a good market fit for the MVP to work I don`t think the full time job was hand in hand it was the worst part ever cause you go full ham mode at you working place and boom you are exhausted also to make some changes I started working early in the morning a head start was always good this made it more easy for the five six months development in early phases of it. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Also The fact is I learn't a good freaking amount of stuff that no one could ever teach me and the bonanza was some dirty office politics :(&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Lesson Four -  Few People But Better People &amp;amp; Connections:
&lt;/h3&gt;

&lt;p&gt;I always was kind of introvert and still I am but now when someone talks about tech I could open up easily, thanks to the corporate world, But No Connections to bigger organisation Engineers and founder, Few to no LinkedIn activities in a consistent manner and also city not that famous for tech I mean It is famous for Affordable development of Products from Scratch but ain't famous for Tech Revolutions, No one speaks tech, no conferences here or there, so building connections was near to impossible all that I had was university and old school friends and random hackathon members here and there, &lt;/p&gt;

&lt;h3&gt;
  
  
  Technically this could be under Lesson Three
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;But Meanwhile Under all this Mess I had got an opportunity to work at India's Silicon Valley, I almost had a dream for building a sustainable start-up many times right when I joined University, I thought I could handle the tech part and someone else could handle the Operations and other stuff related to business, &lt;code&gt;I got a job&lt;/code&gt; but to build a proper product from scratch so I thought I could handle and get away from the mess creating something beautiful for my own product as well joining there and I started loosing attention on my current development plans and sprint's ( Till Now I was only the one who remained working on the product) But I always never loosed hoped on it at that very moment. &lt;br&gt;
Also the Organisation that I was gonna join, where we almost completed our MVP for the product, in a month, backed off but yeah I started getting some good connection as the founder was one of the earliest member of Security at the Fastest growing Quick Commerce Brand (parent company rhymes with TOMATO), also I was not upset as that product was something that help me up-skill more helped me on how to manage product and also product engineering the stuff but yeah this was a important one to address this under this section as my Product where I was only working at that moment got almost killed after this.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Lesson Five - Keep Healthy Lifestyle
&lt;/h3&gt;

&lt;p&gt;Remember last Feb as I said I had an option to join the organisation at the same City, where I completed my University Degree, After few days of my internship got completed, I got diagnosed with CNS-Syndrome due to b-12 deficiency which got me postponed that product to four or five months away which got me a late start but a good start for my software engineering journey in a real sense, Also I am more focused on health than before.&lt;/p&gt;

&lt;p&gt;I didn't have anything to write more than this at this point While Contributing to my Second Product I am more focused to not follow this above points, but also this time I am not in a situation where &lt;code&gt;too many cooks spoil the broth&lt;/code&gt; I am working by myself, No extra attention needed, also in the phase of MVP building this time I would prefer to product market fit after I complete MVP development (this is also an experiment) Ya, I do it a lot, My Life is now based on experiments😅&lt;/p&gt;

&lt;p&gt;That's all Love you guys, Now After my React-Query Series I got around 6k+ Views on my blogs and meanwhile I was unaware about the numbers, hence when I checked that, I thought of writing a one to thank each of the 313 followers also to some I followed back on github. &lt;/p&gt;

&lt;p&gt;If you got till here Get this blog a like and bookmark it to read it in future if you loved it share with someone who can avoid getting into this mess as I did &lt;/p&gt;

&lt;p&gt;Looking Forward, I need to focus on my next product Bye:)&lt;/p&gt;

</description>
      <category>product</category>
      <category>productengineering</category>
      <category>opensource</category>
      <category>programming</category>
    </item>
    <item>
      <title>JS &amp;&amp; Operator Quirks: Better Approaches?</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 01 Jan 2024 06:47:42 +0000</pubDate>
      <link>https://dev.to/delisrey/js-operator-quirks-better-approaches-knj</link>
      <guid>https://dev.to/delisrey/js-operator-quirks-better-approaches-knj</guid>
      <description>&lt;p&gt;Hello everyone! It's been a while, and I hope you're all doing well. Reflecting on the past year, I'm thrilled about the strides I made in my writing journey, sharing insights and experiences through my blogs. Here's to more growth and compelling stories in the coming year! Also Happy New Year!&lt;/p&gt;




&lt;p&gt;Without further ado lets roll with the title above, Recently on the internet I saw &lt;a href="https://twitter.com/t3dotgg" rel="noopener noreferrer"&gt;Theo&lt;/a&gt; explaining what's wrong with the using of &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator in js while returning inside of a functional component.&lt;/p&gt;

&lt;p&gt;Let me explain, What I mean't above by my code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; export default function App() {
  const people = ["deliSrey", "deli", "Srey"];
  return (
    &amp;lt;div className="App"&amp;gt;
      {people.length
        &amp;amp;&amp;amp; people.map((_people, index) =&amp;gt; {
            return &amp;lt;li key={index}&amp;gt;{_people}&amp;lt;/li&amp;gt;;
          })}
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;It result's something like this:&lt;/p&gt;

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




&lt;blockquote&gt;
&lt;p&gt;You might think What's wrong in it There is nothing wrong in it, but also there is something not correct about It, here it could result in a potential bug if you see in a hindsight &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For Example If there is nothing inside the people array list and hence the people.length is 0 which by default returns 0 &lt;br&gt;
rendered on the screen something like this, Here is the code and result attached:&lt;/p&gt;

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

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




&lt;p&gt;Above is how ternary operator replaced by &lt;code&gt;&amp;amp;&amp;amp; operator&lt;/code&gt; looks like, which almost make sense but not in case of nested ternaries:&lt;/p&gt;




&lt;p&gt;With Nested Ternary :&lt;/p&gt;

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




&lt;blockquote&gt;
&lt;p&gt;But now What should we do instead, Should we go towards ternary operator, I mean it is a praticed way but in the same video &lt;code&gt;Theo&lt;/code&gt; explained an interesting way to do it. When there are way more ternary operators nested for checking out multiple conditions, which create a bitter mess and the code is almost unreadable, we can break it into Components,That's where the beauty of React lies, split the nested stuff into the functional components &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;here's how it is :&lt;/p&gt;

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

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




&lt;p&gt;In case where the people array list is empty :&lt;/p&gt;

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

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

&lt;p&gt;Here you can see how the readability and flow of the code is maintained more accurately and hence while working in a team It makes perfect sense to maintain the code quality where the code can be easy to debug and can be easily improved with new features.&lt;/p&gt;

&lt;p&gt;That's all in this blog, I guess If you have already came up til here, You might also try smashing your thumb on follow and like button Trust me it helps my blog to reach more people like you and me!&lt;/p&gt;

&lt;p&gt;Also Special Thanks to the &lt;code&gt;W&lt;/code&gt; Engineer &lt;a href="https://twitter.com/t3dotgg" rel="noopener noreferrer"&gt;Theo&lt;/a&gt; For putting this in his video which inspired me to write a blog on it as well also here is the link to the &lt;a href="https://youtu.be/mOwZhb9bZ5s?feature=shared" rel="noopener noreferrer"&gt;video&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Until then it's a huge goodbye fellas!&lt;/p&gt;

</description>
      <category>react</category>
      <category>typescript</category>
      <category>beginners</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>How to Preview Images before Upload in React.js with textarea dynamically increasing Modal's height ♥</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 09 Oct 2023 04:16:43 +0000</pubDate>
      <link>https://dev.to/delisrey/how-to-preview-images-before-upload-in-reactjs-with-textarea-dynamically-increasing-modals-height-4mj0</link>
      <guid>https://dev.to/delisrey/how-to-preview-images-before-upload-in-reactjs-with-textarea-dynamically-increasing-modals-height-4mj0</guid>
      <description>&lt;p&gt;Hello Folks on the internet, mostly from last few days I was revolving around react-query but now tbh, I was not getting enough escape from my task and at night I use to play valorant to release some dopamine and feel pleasurable, Today Morning I was contributing to my own &lt;a href="//www.bingevoid.com"&gt;product &lt;/a&gt; which I am building from scratch and I found something very noticable their are many blogs on Drag and Drop API but there are few on building the image selection and preview it from scratch, so here I got the idea of making a great one using TS. (By the way I have seen lot of it lately, People are moving from TS to JS especially the contributors to library. With no further Ado Lets Jump in Straight towards the blog.&lt;/p&gt;




&lt;p&gt;Lets start with some basic jsx code to render a modal which takes some values as input and also a image button to add a image which we can preview.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   &amp;lt;div className='parent_modal_input_container'&amp;gt;
      &amp;lt;div className='input-container'&amp;gt;
        &amp;lt;textarea
          maxLength={250}
          onChange={handleChange}
          placeholder='Random Thoughts? :/ Enter here '
          className='input_text_area'
          rows={textareaRows}
          autoFocus={true}
         /&amp;gt;
       &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay in the above piece of code we create a basic jsx to render on the page where i guess there is some parent element with div tag and also a textarea with a maximum length of 250 characters and also added rows to make the card or i might say parent element grow it size with the number of rows increased. so there I took a state to keep a track of rows i.e. with  textareaRows; also apart from that I have added the onChange property when users starts typing we incur with a handleChange function. &lt;/p&gt;

&lt;p&gt;As we added states for two things one to keep a track of textareaRows and the other is the content as the user types here is the code for that...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const [textContent, setTextContent] = useState&amp;lt;string&amp;gt;("")
 const [textareaRows, setTextareaRows] = useState&amp;lt;number&amp;gt;(1);
 const [selectedFiles, setSelectedFiles] = useState&amp;lt;File[] | null&amp;gt;(); // let us discuss this later.

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

&lt;/div&gt;



&lt;p&gt;Moreover as we start towards the image preview and upload functionality we need to create the button and input where it have file type which accepts &lt;code&gt;image/*&lt;/code&gt; that is image with all the formats of its jpg, jpeg, png etc. so here we define the input tag below wrapped inside a button (before you find css in the entire blog I must say, I didnt add css cause i dont want to make a blog too big keep it very cut to short with essential parts! )&lt;/p&gt;

&lt;p&gt;Here is the input tag with the same stuff we talked about&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;button&amp;gt;
    &amp;lt;label&amp;gt;
      &amp;lt;input type='file' accept="image/*" className='hidden'  
        multiple={false} onChange={(e) =&amp;gt; uploadFile(e)} /&amp;gt;
         &amp;lt;ImageIcon width={25} height={25} /&amp;gt;
      &amp;lt;/label&amp;gt;
  &amp;lt;/button&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;Here I have used svg's with the most specific thing that is svg's as ReactComponent and it requires very special addition to typescript and if in specific you are adding a vite bundler to bundle things up.&lt;/p&gt;

&lt;p&gt;Let start with some basic steps towards our functionality and add handleChange function,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const textareaLineHeight = 24; // Adjust this value according to your styling
    const minRows = 1;
    const maxRows = 5; // Adjust as needed

    const previousRows = e.target.rows;
    e.target.rows = minRows; // Reset the rows to the minimum

    const currentRows = Math.floor((e.target.scrollHeight - textareaLineHeight) / textareaLineHeight) + 1;

    if (currentRows === previousRows) {
      e.target.rows = currentRows;
    }

    if (currentRows &amp;gt;= maxRows) {
      e.target.rows = maxRows;
      e.target.scrollTop = e.target.scrollHeight;
    }

    setTextContent(e.target.value);
    setTextareaRows(currentRows);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;hence in the above code we added a minimum rows up to 1 and maximum rows upto 5 with a variable defined previous rows , current rows, previous rows is nothing but the event.target.rows which is defined by the dom event parameter. and current rows is the floor value of (e.target.scrollHeight - textareaLineHeight)/ textareaLineHeight why this cause this is the portion where we add the stuff for dynamically increasing the parents size when the row size increases by defining the current row hence if we say that the currentRow = 1 it means the scroll height would be 24 and hence &lt;code&gt;[{(24-24)/24} + 1]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;hence if the text overflows and starts to the next line the value of the current rows increases and becomes 2 with the scroll height with value 48 hence it all revolves around the initial value of textareaLineHeight.&lt;/p&gt;

&lt;p&gt;Moreover if you see there is an unusal behaviour it oscillates between the rows that is current and previous rows why does this happens is very clear as we are defining this stuff inside the onChange parameter hence to make sure it works smooth upto some extent is our target and we can do it by a very special and beloved stuff a debounce function by lodash ( why lodash my project is already have lodash so i might use it but to build it from sratch is very simple here you go with this &lt;a href="https://www.freecodecamp.org/news/javascript-debounce-example/" rel="noopener noreferrer"&gt;link&lt;/a&gt; but I might say what does debounce do, it delays the function with the milliseconds as argument hence upto that millisecond it will delay the function this will make something good to us I promise :)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const debouncedHandleChange = debounce((e: React.ChangeEvent&amp;lt;HTMLTextAreaElement&amp;gt;) =&amp;gt; {
    const textareaLineHeight = 24; // Adjust this value according to your styling
    const minRows = 1;
    const maxRows = 5; // Adjust as needed

    const previousRows = e.target.rows;
    e.target.rows = minRows; // Reset the rows to the minimum

    const currentRows = Math.floor((e.target.scrollHeight - textareaLineHeight) / textareaLineHeight) + 1;

    if (currentRows === previousRows) {
      e.target.rows = currentRows;
    }

    if (currentRows &amp;gt;= maxRows) {
      e.target.rows = maxRows;
      e.target.scrollTop = e.target.scrollHeight;
    }

    setTextContent(e.target.value);
    setTextareaRows(currentRows);
  }, 130);

  const handleChange = (e: React.ChangeEvent&amp;lt;HTMLTextAreaElement&amp;gt;) =&amp;gt; {
    debouncedHandleChange(e);
  };

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

&lt;/div&gt;



&lt;p&gt;Remember we discussed the stuff before while declaring state we left one of it there the selectedFile stuff that is used to keep track for the files when the input is given that is when the button is clicked the upload function runs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const uploadFile = (e : 
   React.ChangeEvent&amp;lt;HTMLInputElement&amp;gt;) =&amp;gt; {
    if(!e.target.files || e.target.files.length === 0){
      setSelectedFiles(undefined);
    }
    if(e.target.files){
      setSelectedFiles([e.target.files[0]])
    }    
} 

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

&lt;/div&gt;



&lt;p&gt;so what we did above is nothing we made a check for if the target.files exist and its length should be greater than 0;&lt;br&gt;
if it is then we use the setter method in our case our setterState dispaches and it sets the e.target.files[0] why 0 make sure you do a console.log you will get to know :)&lt;/p&gt;

&lt;p&gt;lets print it out i mean render it out&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className='parent_modal_input_container'&amp;gt;
   &amp;lt;div className='input-container'&amp;gt;
     &amp;lt;textarea
       maxLength={250}
       onChange={handleChange}
       placeholder='Random Thoughts? :/ Enter here '
       className='input_text_area'
       rows={textareaRows}
       autoFocus={true}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
 &amp;lt;/div&amp;gt;
 {
   selectedFiles &amp;amp;&amp;amp; selectedFiles.map((file, key) =&amp;gt; {
    return (
     &amp;lt;div key={key} className="row mt-2 relative"&amp;gt;
       &amp;lt;span className="filename"&amp;gt;
         &amp;lt;img className='rounded-md h-[150px] md:w-[500px] md:h- 
            [400px] m-auto' src={URL.createObjectURL(file)} alt= 
            {file.name} /&amp;gt;
         &amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
     )
   })
  }

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

&lt;/div&gt;



&lt;p&gt;So whats left, I dont think so much is left we also need to remove the image if some one wants to make a new image selected from the input field that we defined, so hence for doing that we might handle it using making selectedFiles set to undefined so this will remove it from the selectedFiles state contianing array. &lt;/p&gt;

&lt;p&gt;Okay that is not something major, but we will make it more interesting defining it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   selectedFiles &amp;amp;&amp;amp; selectedFiles.map((file, key) =&amp;gt; {
    return (
     &amp;lt;div key={key} className="row mt-2 relative"&amp;gt;
       &amp;lt;span className="filename"&amp;gt;
         &amp;lt;img className='rounded-md h-[150px] md:w-[500px] md:h- 
            [400px] m-auto' src={URL.createObjectURL(file)} alt= 
            {file.name} /&amp;gt;
         &amp;lt;/span&amp;gt;
         &amp;lt;section&amp;gt;
           &amp;lt;button onClick={() =&amp;gt; removeFile([file])}&amp;gt;&amp;lt;CloseIcon 
             className='absolute top-0 right-[20%] md:right-[5%] 
             h-[22px] w-[22px] md:h-[30px] md:w-[30px]' /&amp;gt;
            &amp;lt;/button&amp;gt;
         &amp;lt;/section&amp;gt;
      &amp;lt;/div&amp;gt;

     )
   })
  }

// here is the function :()

  const handleRemovePhotoFile = (selected: File[]) =&amp;gt; {
    const filteredFileData = selectedFiles?.filter(
     (_file) =&amp;gt; _file !== selected[0]);
    setSelectedFiles(filteredFileData);
  };

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

&lt;/div&gt;



&lt;p&gt;To be very honest their is one more bug if you followed along up till now you might have known it only allows you to get the image selected for the first time but after you remove it , it dont (for me i had only one image on my system so it didn't work hence i got a way after i passed in something wanna take a guess I spent completley more than 45 mins thinking what is wrong hence just add something to our input of file like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type='file' accept="image/*" className='hidden' multiple={false} onChange={(e) =&amp;gt; uploadFile(e)} value={""} /&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;You Got it Right ?? &lt;/p&gt;

&lt;p&gt;The value parameter we forgot to add, oh silly me but yeah I got to over-think that i should reset e.target.files or make it null, but finally as a fraction of my attention went to input tag and asked where is value that is initially defined and here i got it so that's why i say I write code and mostly it is shitty 🃏!&lt;/p&gt;

&lt;p&gt;But there is one more thing left if you see and fix it please comment it down cause I already have fixed it If you can find it Please just let the people know how cool are you finding the bugs!&lt;/p&gt;




&lt;p&gt;So that's all if you have reached till here you might have liked it and i might have added some value to you if it is so please drop a like and save I guess it will make my day!&lt;/p&gt;

&lt;p&gt;That's all folks I might be a shitty coder But I am great debugger Haha Just Kidding I do worst at both Btw have a look at my product as well Kinda making my life harder working at it but i love it though &lt;/p&gt;

&lt;p&gt;Thats all Have a great week ahead ! GoodBye Fellas!&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>React Query as State Manager</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 02 Oct 2023 12:34:46 +0000</pubDate>
      <link>https://dev.to/delisrey/react-query-as-state-manager-1l88</link>
      <guid>https://dev.to/delisrey/react-query-as-state-manager-1l88</guid>
      <description>&lt;p&gt;Up til now we mostly discussed data fetching and mutating using react-query but is it all , has it got any more things just than fetching and mutating stuff the answer is it can also be a asynchronous state manage instead we should say that react-query is a async state manager and small part of it consist of the network activity.&lt;br&gt;
Alright Lets start with React-Query as State Manager!&lt;/p&gt;


&lt;h3&gt;
  
  
  React Query as State Manager
&lt;/h3&gt;

&lt;p&gt;So how is it possible to maintain state globally using react-query, in the initialisation of our series we started with some basic terminologies such as &lt;code&gt;queryKey&lt;/code&gt; so their we mentioned that it maintains the data fetching call/query uniquely with a key which unleashed some power and this is the power we were talking about the &lt;code&gt;queryKey&lt;/code&gt;, react-query shines out until we feed the promises ( I mean till the time we do data fetching cause data fetching mostly produce promises); so if I call query at two different places in my codebase with the same queryKey it will give me the same data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Place1 () {
const {data : spotifyData} = useSpotifyData();
----
-----
-----
----
} 

function Place2 () {
const {data : spotifyData} = useSpotifyData();
----
----
----
----
}

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

&lt;/div&gt;



&lt;p&gt;here if we see both the component calls the same custom hook which abstracts out the useQuery() data fetching function to be written again and again and have a query-key in common which renders the same data.&lt;/p&gt;

&lt;p&gt;But how do we keep the data synchronize then ?&lt;/p&gt;

&lt;p&gt;Yes this too have an answer, the react-query being a server state library this have nothing to do where front-end can own the data , if we display the data on front-end than it is always the one which is fetched from API and we just render the small parts of it , so for example the application like instagram where a user posts the photos and the comments and likes are changing real time , how much of it is accurate (by accurate I mean how much of them is stale, as it changes from fresh to stale very fast)&lt;/p&gt;

&lt;h3&gt;
  
  
  Lets see how react query synchronises the data
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Loader or some Data that is stale ?
&lt;/h4&gt;

&lt;p&gt;React-query is very famous for its caching mechanism hence react-query prepares &amp;amp; cache the data whenever you need to render it on front-end even if it is stale data as users might not like some loading state or no data until freshly brewed data renders on screen.&lt;/p&gt;

&lt;p&gt;Moreover to decide when is to re-validate stale data that is making a query to the back-end interface for fresh data and to be keeping our re-renders in-expensive we need to make some great decision for re-fetch  &lt;/p&gt;




&lt;p&gt;When we can do the refetches then ?&lt;/p&gt;

&lt;p&gt;refetchOnWindowFocus : This might seem crazy when we are in a development mode but in production this do make sense , as it revalidates whenever we focus or switch the browser tabs , but when user does this after leaving application open for a long time and then if the user returns to the application, hence feeding the fresh data will always be great.&lt;/p&gt;

&lt;p&gt;refetchOnReconnect : whenever you loose the connection and re-gain it will revalidate at that point of time &lt;/p&gt;

&lt;p&gt;refetchOnMount : this revalidates happen's when the component having the query useQuery mounts &lt;/p&gt;




&lt;p&gt;That's all Folks This blog was small I know but this will be paving a good road-map ahead making our journey more beautiful, well until next time its a goodbye &lt;/p&gt;

&lt;p&gt;If you are till here , please drop some feedback or like the blog, Goodbye&lt;/p&gt;

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

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>typescript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Fetching &amp; Mutating Data with React-Query</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Wed, 20 Sep 2023 10:10:59 +0000</pubDate>
      <link>https://dev.to/delisrey/fetching-mutating-data-with-react-query-395f</link>
      <guid>https://dev.to/delisrey/fetching-mutating-data-with-react-query-395f</guid>
      <description>&lt;p&gt;Hello again, you might found me lame, messing things around but React Query would never be !&lt;/p&gt;

&lt;h3&gt;
  
  
  How can be fetching done in React Query ?
&lt;/h3&gt;

&lt;h6&gt;
  
  
  if you ever thought the above question lets deep dive than !
&lt;/h6&gt;




&lt;p&gt;If you are inside the react.js community , you might have heard useQuery hook or might be if you read my last part of this series you might have knew it ; Does it ring a bell if not don't worry we will see what useQuery hook is !&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;useQuery&lt;/code&gt; is a hook inside the react-query which manages different things for eg (inital Data fetching , loading states , refetching etc) this all stuff that too asynchronously in background !&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const getuser = () =&amp;gt; {
  return axios.get("/api/v1/me");
}


const {
   data: response,
   isLoading,
   isError,
 } = useQuery(["fetch-s-history"], () =&amp;gt; getUser());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here in the above piece of code if we see the useQuery hook expects a queryKey which indeed is an array and a query function that returns the API response as promise untill you do it asynchronously, Moreover it has many more parameters that we can add like enabled (which is of great use though) wait we will explore together I swear!&lt;/p&gt;

&lt;p&gt;Hence the useQuery Hook returns the data in our case response as we gave it an alias hence the response can be used across the code-base if we made a custom hook for it and return the same thing without destructing any of below&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;{data , isLoading , isError}&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Does key unleash some power ?
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Yes it does the queryKey helps in caching the data independently, when any dependency inside the query changes, the refetch of the query occurs on the basis of staleTime , so you might be wondering what exactly is a dependency, if you know React that I guess you do you may know the working of &lt;code&gt;useEffect()&lt;/code&gt; hook it takes some dependency inside the dependency array to re render the component if you don't add any by default the useEffect will run your custom logic written inside the hook and it will get called after performing all the DOM updates.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's see exactly what I said&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type todoState = "done" | "pending" | "all"

type todo = {
 id : number ;
currentState : todoState;
}

type todoProps = Array&amp;lt;todo&amp;gt;

const queryClient = new QueryClient(); 

const fetchTodos = async (state: todoState): Promise&amp;lt;todoProps&amp;gt; =&amp;gt; {
 return await axios.get(`api/get/todo/${state}`)
}

export const useFetchQueryTodos = (state : todoState) =&amp;gt; {
useQuery({
    queryKey: ['todos', state],
    queryFn: () =&amp;gt; fetchTodos(state),
    initialData: () =&amp;gt; {
      const allTodos = queryClient.getQueryData&amp;lt;todoProps&amp;gt;(['todos', 'all'])
      const filteredData =
        allTodos?.filter((todo) =&amp;gt; todo.currentState === state) || []
      return filteredData.length &amp;gt; 0 ? filteredData : undefined;
)}
}

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

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;So if we see above, the piece of code changes when the user changes the currentState of the todo like from done to pending or pending to done , hence the data will be fetched and then we can filter the data on that basis if we need done we have a state matching it with the todo.currentState and if its pending state it follows the same set of instruction.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's talk about enabled as we left it while we were discussing the querykey&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;so What can we do is we can make a query dependable for example if a query1 gets depended on a id which I get from a different query2 so we can make our query1 dependable on query2 here it is how :&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {data : products} = useQuery({
  queryKey: ['products'],
  queryFn: getProductData,
})

const productId = product?.id


const {data : productDetail ,
isLoading : isproductDetailLoading } = useQuery({
queryKey :["product-detail],
queryFn : () =&amp;gt; getProductFn(productId),
enabled : !!productId
})

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

&lt;/div&gt;



&lt;p&gt;So here in above example we can see we fetched the productDetail using the useQuery hook but we allowed the query on when there is a enabled state is set to true (cause enabled take a boolean value) hence if you want to disable a query from running automatically we go and make enabled parameter to &lt;code&gt;false&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;so does it mean we only make a query disable using enabled parameter that`s not the case , we can also make it enable later at anytime as you can see in my above example where I took the productId and allow a query when the value of enabled is turned to true ,&lt;/p&gt;

&lt;h4&gt;
  
  
  But what if enabled is false ?
&lt;/h4&gt;

&lt;p&gt;Lets get to that case &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;if query have a cache , then the query initialized with the status of success&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;the query will not automatically fetch on mount and also it will not refetch automatically in the background&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The query will ignore query client invalidateQueries and refetchQueries calls that would normally result in the query refetching. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Also if it does not have cache data the query status will be set to loading &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  UseMutation hook ...
&lt;/h3&gt;

&lt;p&gt;(the state keeping track for mutation  😌)&lt;/p&gt;

&lt;p&gt;So what is mutation ;&lt;/p&gt;

&lt;p&gt;Mutation for example when we login using our email and password the server returns us a token as a response hence it is just a classic example of managing a server state with useMutation hook , For a better definition remember Dominik? &lt;br&gt;
(the guy who saved me from falling inside a trap) He got a great definition for this hook &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;As the name indicates, useMutation also has some sort of side-effect. Since we are in the context of managing server state with React Query, mutations describe a function that performs such a side effect on the server. Creating a todo in your database would be a mutation. Logging in a user is also a classic mutation, because it performs the side effect of creating a token for the user.&lt;br&gt;&lt;br&gt;
                               -- &lt;a href="https://tkdodo.eu/blog/mastering-mutations-in-react-query" rel="noopener noreferrer"&gt;Dominik's blog&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's dive with an example on useMutation Hook &lt;br&gt;
(bear with me my code blocks has some issue i promise the white screen will never be back again )&lt;/p&gt;

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

&lt;p&gt;you heard me saying sideEffect, So what is a sideEffect ? &lt;/p&gt;

&lt;p&gt;In react we say a side-effect is when we perform something outside the scope of react , so in react-query we say this in the context of managing state server side hence when we create something like making a signup API hit and making a mutation on the database ; making a database entry for that particular user.&lt;/p&gt;

&lt;p&gt;So there are many similarities between useQuery and useMutation, but as we saw in react-query run queries automatically and also smartly runs in background for some data updates to keep client and server in sync , but what if the mutation just follow the same way , if i wanted to add a list of users on my application , and each time if it run the mutate query every time my browser window focus so we dont make it run immediately but we can make them run on some action for example i create a add button beside the user i want to add and invoke a function but wait which function might be {mutate : mutatioFn} &lt;/p&gt;

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

&lt;p&gt;so in a way we can say mutateFn with the help of useMutation() hook that we wrote will only invoke when we want to mutate something like updation of profile or addition of new password etc.&lt;/p&gt;

&lt;p&gt;One more thing is that we can use useQuery (as it have a state shared) hence we can make a query run in different component and return the same cache data but it wont with the useMutation hook &lt;/p&gt;

&lt;p&gt;Thats all from my side, but want to have a good look in it untill I publish further have a look on &lt;a href="https://tkdodo.eu/blog/mastering-mutations-in-react-query" rel="noopener noreferrer"&gt;Dominik's blog&lt;/a&gt; and React-Query docs as well up-till then have a look at cleaning the code we usually used to mess with  React-Query &lt;/p&gt;

&lt;p&gt;Thanks for the amazing response on the first two part, Good Bye Fellas. &lt;/p&gt;

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

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>React Query : staleTime vs cacheTime</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Sat, 16 Sep 2023 12:27:01 +0000</pubDate>
      <link>https://dev.to/delisrey/react-query-staletime-vs-cachetime-hml</link>
      <guid>https://dev.to/delisrey/react-query-staletime-vs-cachetime-hml</guid>
      <description>&lt;p&gt;So in our last part we looked the basics of default configuration and also looked at the concepts of stale time and cache time, but what should be ideally the case, how to make it the best possible scenario by assigning the values to them respectively.&lt;/p&gt;

&lt;p&gt;Ideally many of you will also think are they both inter-related? I might not have the best answer for it but lets have a look into it and find out,  (TLDR : Answer is no)&lt;br&gt;
Shall we?&lt;/p&gt;




&lt;h3&gt;
  
  
  Does Setting Any One of them Impacts other ?
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;staleTime basically is the time before the data fetched again from server gets stale or we may say the data that haven't been updated, as in my last part of this series I mentioned the default time of staleTime is set to be 0 in react-query hence when the data gets fetched it is considered to be stale&lt;br&gt;&lt;br&gt;
and hence the data gets re fetched again if you open your networks tab you will see multiple API request firing from client side. So does cacheTime gets impacted from this , no cacheTime is a length of time which removes the inactive data or stale data after a certain amount of time by default 5 mins from cache , so stale data is something that is responsible for making API request when data gets stale or when fresh or updated data is needed.&lt;/p&gt;
&lt;/blockquote&gt;




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




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




&lt;h2&gt;
  
  
  Let's see What scenarios rises when we go with default configurations!
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Data Fetch: When you fetch data using React Query, the data will be considered fresh and not stale at the time of the initial fetch.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Immediate Staleness: Since you've set staleTime to zero, as soon as the initial data is loaded, it will be marked as stale. This means that if you try to access the same data again, React Query will consider it stale and attempt to refetch it immediately.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cache Retention: Since you didn't specify a value for cacheTime, React Query will use its default behavior. By default, data will be retained in the cache for 5 minutes (cacheTime of 300,000 milliseconds). After that time elapses, the data will be automatically removed from the cache.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Continuous Refetching: Because the data is immediately marked as stale and React Query will try to refetch it, you'll likely see frequent network requests for the same data as long as the data remains in the cache (up to the default cacheTime of 5 minutes). This can potentially result in a high volume of network requests for the same data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;In summary, setting staleTime to zero and not specifying a custom cacheTime will lead to immediate staleness of fetched data and frequent refetching as long as the data remains in the cache, which is retained for the default 5-minute duration. This behavior might not be desirable in most cases because it can result in unnecessary network requests. You should carefully consider the appropriate values for staleTime and cacheTime based on your application's requirements to achieve the desired caching and data freshness behavior.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  So What should happen if we set cacheTime lower Than staleTime
&lt;/h2&gt;

&lt;p&gt;Huh! its all about timing (no puns intended)&lt;/p&gt;

&lt;p&gt;So now If we set &lt;code&gt;staleTime : 15 mins&lt;/code&gt; and cacheTime : &lt;code&gt;5 mins&lt;/code&gt; for example just grab a minute and think what should happen &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If client sends a request for the first time , the backend interface sends the data requested and the staleTime set to 15 mins make data to be considered as fresh for that amount of time &lt;br&gt;
But now the User on client side jumps on different application or tab , and return after 10 minutes so he should have the data to be rendered on client side should be fresh , but cacheTime as set to be 5 minutes which is lower than staleTime hence the data will not be fetched from cached data  we need to make a re fetch for the data from the backend interface even though the data is not stale it is refetched it doesn't make sense, right ? &lt;/p&gt;
&lt;/blockquote&gt;




&lt;h5&gt;
  
  
  Thanks to &lt;a href="https://twitter.com/TkDodo" rel="noopener noreferrer"&gt;Dominik&lt;/a&gt; (react-query maintainer)for this correction (This is the updated part after we had the &lt;a href="https://twitter.com/shreykoradia/status/1703366027185111146" rel="noopener noreferrer"&gt;convo&lt;/a&gt; on twitter)
&lt;/h5&gt;

&lt;h6&gt;
  
  
  That above thing that you thought or I thought is not correct cause cacheTime is not about something as the name suggest it is indeed something like when a user is on &lt;code&gt;/me&lt;/code&gt; route and if he goes to a different route &lt;code&gt;/feeds&lt;/code&gt; for example than the cacheTime get kicks in as query becomes inactive or unused hence if the user doesn't comeback to the same route&lt;code&gt;/me&lt;/code&gt; under 5 mins which is our default time for cacheTime than the data from the cache gets removed silently and hence a manual refetch would be needed as the cacheTime or staleTime will not automatically have refetch running. Moreover in version 5 it had been renamed to &lt;code&gt;gcTime&lt;/code&gt; and hence setting it lower than staleTime doesn't make any difference
&lt;/h6&gt;

&lt;p&gt;Here is the &lt;a href="https://github.com/TanStack/query/issues/4678" rel="noopener noreferrer"&gt;github_issue&lt;/a&gt; referencing for the same &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;There will be many articles where you find the same reasoning on cacheTime where I got mistaken but thanks to Dominik ( React-Query maintainer) for pointing out my mistake &lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  Configuring Stale Time &amp;amp; Cache Time For a Particular API request
&lt;/h3&gt;

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

const { data } = useQuery(['my-data'], fetchMyData, { 
  staleTime: 10 * (60 * 1000), // 10 mins 
  cacheTime: 15 * (60 * 1000), // 15 mins 
});


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

&lt;/div&gt;




&lt;h3&gt;
  
  
  Configuring StaleTime &amp;amp; CacheTime Globally
&lt;/h3&gt;

&lt;p&gt;So if you want all of your data to be considered fresh for longer - you can! Instead of changing cacheTime and staleTime on useQuery, you'll set it on the QueryClient.&lt;/p&gt;

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

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 10*(60*1000), // 10 mins
      cacheTime: 15*(60*1000), // 15 mins
    },
  },
});



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

&lt;/div&gt;

&lt;p&gt;Meet You again with the new part of this series, if you got something valuable and if you liked it (I know cause You are reading this) please drop a feedback it will be helpful to make this journey more better.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/kY79vfXzenZMpi0GrN/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/kY79vfXzenZMpi0GrN/giphy.gif" alt="meme"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>What the heck is React-Query?</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Fri, 15 Sep 2023 11:51:34 +0000</pubDate>
      <link>https://dev.to/delisrey/what-the-heck-is-react-query-457d</link>
      <guid>https://dev.to/delisrey/what-the-heck-is-react-query-457d</guid>
      <description>&lt;p&gt;Heard about maintaining your states globally when you need the data across the components either we can do it on the client side maintaining the cache data using some store or state management library or we can make the ultimate move now using React Query !&lt;/p&gt;




&lt;h2&gt;
  
  
  What is React Query then ?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;React Query is a server state library for managing the asynchronous client and server operation and actions reducing the boiler code that used to be a part when you add a client state management library probably React-Redux ! if you develop application in React.js &lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  How to use React Query efficiently and does it replaces the state management libraries ?
&lt;/h3&gt;

&lt;p&gt;It might be not possible to replace the libraries when the application is very complex or it has very complex modal structures or simply we can say application like music production for example (FL studio)  otherwise React Query is the perfect choice with no issues. &lt;/p&gt;

&lt;p&gt;The Docs as well is almost perfect to get started and play along with the queries to see what happens and why !&lt;/p&gt;




&lt;h3&gt;
  
  
  Lets Start with the basics of React Query
&lt;/h3&gt;

&lt;p&gt;The React Query have a great default configs but what are they and what do it mean is a great thing to understand if you want to work on react-query efficiently I rewrite these in my code-base where I write the QueryClient Provider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        refetchOnWindowFocus: false,
        retry: 1,
      },
    },
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So here if we see we tried to overwrite the default configuration of the QueryClient(), where we did a &lt;code&gt;refetchOnWindowFocus:false&lt;/code&gt; cause we don't want to refetch data by calling API's every time our browser window gets focused after everytime we switch the tabs on our browsers &lt;br&gt;
so what is &lt;code&gt;retry&lt;/code&gt; retry is the number of times the query re-runs before showing the error message displayed by the &lt;code&gt;onError&lt;/code&gt; method or any custom logic written inside the fucntion, for example &lt;code&gt;retry: fasle&lt;/code&gt; will not allow any query re-run.&lt;/p&gt;

&lt;p&gt;I know I know , you are getting a lot of question , question on how the data gets updated inside the query-call or what if my data doesn't get updated&lt;/p&gt;

&lt;p&gt;The concept you need to look is &lt;code&gt;staleTime&lt;/code&gt; , so what in freaking world is &lt;code&gt;staleTime&lt;/code&gt;, it is the length of time before your data becomes stale. By default the staleTime in react-query is 0 , which means immediately your data is consider to be stale &lt;/p&gt;

&lt;p&gt;If your data is fresh it will be cached or saved and it will be used repeatedly without making API calls to the server &lt;/p&gt;

&lt;p&gt;So you might be thinking will be there any cache time for caching the data again if there is any changes inside the data coming from server , by the way We do have &lt;code&gt;cacheTime&lt;/code&gt; it is the time before the cached or inactive data gets removed.&lt;/p&gt;

&lt;p&gt;In react-query cacheTime by default is set to 5 mins and hence we need to carefully choose it and the difference between them is great to understand how react-query works and to set both staleTime and cacheTime is a little bit of challenge moreover we will see in the next part how we can make it a piece of ease by seeing in depth how it works &lt;/p&gt;

&lt;p&gt;Till then its a great goodbye from my side if you want to learn it from official docs &lt;a href="https://tanstack.com/query/latest/docs/react/guides/important-defaults" rel="noopener noreferrer"&gt;React-Query&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Untill Next time !&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/WiM5K1e9MtEic/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/WiM5K1e9MtEic/giphy.gif" width="245" height="180"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactquery</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Stack DataStructure in JS</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Mon, 05 Jul 2021 07:02:36 +0000</pubDate>
      <link>https://dev.to/delisrey/stack-datastructure-in-js-2176</link>
      <guid>https://dev.to/delisrey/stack-datastructure-in-js-2176</guid>
      <description>&lt;h5&gt;
  
  
  // hello virtual folks !
&lt;/h5&gt;

&lt;h6&gt;
  
  
  # Lets give a shot to Stack without further ado
&lt;/h6&gt;

&lt;p&gt;Stack as everybody know what it means Stack is nothing but a vector representing a list of elements  that follows a particular order that is LIFO while they are deleted or removed or printed out .&lt;/p&gt;

&lt;p&gt;Here is the code for the Stack implementation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Stack Is nothing but a vector that follows LIFO order , it has // push , pop and peep as main Functionalities&lt;/span&gt;


&lt;span class="c1"&gt;// defining a class stack first off all &lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Stack&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// array(vector) is used to implement the stack &lt;/span&gt;

        &lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
            &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets add the code for Push and Pop operation and also Peek&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;  &lt;span class="c1"&gt;// now lets create a push function&lt;/span&gt;

        &lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
            &lt;span class="c1"&gt;// push element &lt;/span&gt;
            &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;    
        &lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now we will see how to add code with Pop operation !&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;   &lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
                &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt; UNDERFLOW&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;element&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now here let me take a second of your's and say you why we are checking the condition &lt;/p&gt;

&lt;h4&gt;
  
  
  if the array is empty the pop function inside the code of stack will be having no values to delete  when we solve the question by pointers we take the pointer condition as top = -1 and then we start pushing the values in it by adding pointer to 1 each time we add values to it
&lt;/h4&gt;

&lt;h4&gt;
  
  
  similarly we also need to keep an eye for removing the top element every time in the stack if the stack doesn't contains any value on the vector then it will return us the result of the if part of the code that is Underflow ! and if stack is not empty it will return us the result that we opt for that is the deleted value or element .
&lt;/h4&gt;

&lt;p&gt;Now we see  here how to write code for the peek&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt; &lt;span class="c1"&gt;// peek  return's the top most element but does not delete it &lt;/span&gt;

        &lt;span class="nf"&gt;peek&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;    &lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here is a small additional code for printing the stuff out one by one in Stack datastructure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;
  &lt;span class="c1"&gt;// printStack &lt;/span&gt;
        &lt;span class="nf"&gt;printStack&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
        &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt; &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;feel free to play around through the code and get your hands dirty on this !&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// adding element to the stack for purpose of test &lt;/span&gt;

&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Stack&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;peek&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;


&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;printStack&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;I hope you can get started with the implementation if you were stucked after learning the concept of Stack data Structure Hope you find it interesting , untill then G00D Bye ! &lt;/p&gt;

</description>
      <category>stack</category>
      <category>datastrucutre</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Operator's String And Loop's with a tint of if and else.</title>
      <dc:creator>SREY</dc:creator>
      <pubDate>Thu, 08 Apr 2021 10:41:12 +0000</pubDate>
      <link>https://dev.to/delisrey/operator-s-string-and-loop-s-with-a-tint-of-if-and-else-33b1</link>
      <guid>https://dev.to/delisrey/operator-s-string-and-loop-s-with-a-tint-of-if-and-else-33b1</guid>
      <description>&lt;p&gt;HELLO My dazzling friends from the internet , todays lets start by thinking what is "Operators" or why not 'String' ? &lt;br&gt;
Lets see them one by one :D&lt;/p&gt;
&lt;h4&gt;
  
  
  Operator's
&lt;/h4&gt;

&lt;p&gt;Java divides the operator in the below parts &lt;br&gt;
=&amp;gt; Arithmetic Operators&lt;br&gt;
=&amp;gt; Logical Operators &lt;br&gt;
=&amp;gt; Assignment operators &lt;br&gt;
=&amp;gt; Comparison operators &lt;br&gt;
=&amp;gt; Bitwise Operators&lt;/p&gt;

&lt;p&gt;Arithmetic operators consist of '+','-','*','/',and Increment and decrement ++ and -- respectively and  % (modulo) .&lt;/p&gt;

&lt;p&gt;Comparison operators consist of &amp;gt;,&amp;lt;, &amp;gt;= , &amp;lt;= , == , and != &lt;/p&gt;

&lt;p&gt;Logical operators consist of &amp;amp;&amp;amp;(and) ,||(or) , !(Not) &lt;/p&gt;

&lt;p&gt;Assignment operations are = , += , -= and many more  of this types .&lt;/p&gt;
&lt;h4&gt;
  
  
  String's In java :
&lt;/h4&gt;

&lt;p&gt;Strings are used for storing text , it can be also said as the collection of words stored in double quote's&lt;/p&gt;
&lt;h5&gt;
  
  
  How to create a string variable
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"DELI"&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Other string method's :&lt;br&gt;
length()  ~ for example =&amp;gt; name.length();&lt;br&gt;
toUpperCase();&lt;br&gt;
toLowerCase(); &lt;/p&gt;
&lt;h6&gt;
  
  
  Dribble 【 ͡❛ ͜ʖ ͡❛】 :
&lt;/h6&gt;

&lt;p&gt;There are many more , but all are not of use and if they are in need they can be searched on the internet .&lt;/p&gt;

&lt;p&gt;Now lets see some concatenation &lt;/p&gt;

&lt;p&gt;The + operator can be used between strings to combine them. This is called concatenation &lt;br&gt;
 for example ;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;firstName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Elon"&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt; 
&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nc"&gt;SecondName&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Musk"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"HEY MR "&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;firstName&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;SecondName&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output :&lt;br&gt;
HEY MR Elon Musk &lt;/p&gt;

&lt;p&gt;Some More Dribble :\&lt;/p&gt;

&lt;p&gt;Ever thought of Writing code this way :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;var1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"HEllo"&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;var2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"13 "&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;var3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;var1&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;var2&lt;/span&gt;    &lt;span class="c1"&gt;// output will be HEllo13 &lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;HERe we conclude Strings &lt;/p&gt;

&lt;p&gt;Before we jump on the  Loops lets start with If and else condition's &lt;/p&gt;

&lt;p&gt;Think about what you like to eat between two things that you like  the most , you might be making decisions right ....ok cool forget food for a second If today rains i will be playing and if not i will play .....or there are tons of example , similarly in coding we have set of instruction that we need to select in cases of different context so we use if else or switch &lt;/p&gt;

&lt;h5&gt;
  
  
  format of if else :
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;condion&lt;/span&gt;&lt;span class="o"&gt;){&lt;/span&gt;
&lt;span class="o"&gt;---------------&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;
&lt;span class="o"&gt;--------------&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Switch
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;switch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;expresion&lt;/span&gt;&lt;span class="o"&gt;){&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="k"&gt;break&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Default keyword :
&lt;/h5&gt;

&lt;p&gt;The default keyword specifies some code to run if there is no case match :)&lt;/p&gt;

&lt;h4&gt;
  
  
  Break Keyword :
&lt;/h4&gt;

&lt;p&gt;The break keyword specifies that whenever it is seen it stops the execution in the switch and hence the statement will be printed .&lt;br&gt;
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.&lt;/p&gt;
&lt;h3&gt;
  
  
  Loop's
&lt;/h3&gt;

&lt;p&gt;Loops are written to repeat the specific statements certain time until the condition are met .&lt;br&gt;
Loops saves time , reduction of error and also can make the code DRY (do not repeat yourself)&lt;/p&gt;

&lt;p&gt;There are three loops &lt;br&gt;
=&amp;gt; DO while &lt;br&gt;
=&amp;gt; While and &lt;br&gt;
=&amp;gt; for&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"HEY i Love to Read these JAva series "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
  &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output :&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++){&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"HEY i Love to Read these JAva series "&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output :&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;br&gt;
HEY i Love to Read these JAva series&lt;/p&gt;

&lt;h4&gt;
  
  
  Let's conclude
&lt;/h4&gt;

&lt;p&gt;THis was the basics  of java  it has much things that can be learned in detail if one tries to try competitive coding and learn as much as they can as said learning never stops !&lt;/p&gt;

</description>
      <category>java</category>
      <category>oracle</category>
      <category>java8</category>
      <category>loops</category>
    </item>
  </channel>
</rss>
