<?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>Forem: Rahul Khatri</title>
    <description>The latest articles on Forem by Rahul Khatri (@rahul72925).</description>
    <link>https://forem.com/rahul72925</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%2F800679%2F5b33b197-6cac-4adc-ad67-b0cfcbe96c4b.jpg</url>
      <title>Forem: Rahul Khatri</title>
      <link>https://forem.com/rahul72925</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rahul72925"/>
    <language>en</language>
    <item>
      <title>Custom hooks in React</title>
      <dc:creator>Rahul Khatri</dc:creator>
      <pubDate>Mon, 17 Apr 2023 18:56:47 +0000</pubDate>
      <link>https://forem.com/rahul72925/custom-hooks-in-react-32dm</link>
      <guid>https://forem.com/rahul72925/custom-hooks-in-react-32dm</guid>
      <description>&lt;p&gt;Hey👋 Devs,&lt;/p&gt;

&lt;p&gt;Before get into the topic let's understand what is &lt;strong&gt;hooks&lt;/strong&gt; in React.&lt;/p&gt;

&lt;p&gt;Hooks allow to use state and other React features in functional components, making them more powerful and flexible.&lt;br&gt;
There's already one general hook, &lt;code&gt;useState&lt;/code&gt; that an array and the first element of an array is  &lt;code&gt;value&lt;/code&gt; and second one is a function to update the value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [toggle, setToggle] = useState(false)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above snippet, &lt;code&gt;useState&lt;/code&gt; takes initial value &lt;code&gt;false&lt;/code&gt; as an argument and returning an array, here is &lt;code&gt;toggle&lt;/code&gt; vale and the &lt;code&gt;setToggle&lt;/code&gt; is a function that update the &lt;code&gt;toggle&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; hook has there own logic to provide these value in more efficient way.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Custom Hook?
&lt;/h2&gt;

&lt;p&gt;A Custom Hook is a function that allows to extract logic from a component and reuse it across multiple components. &lt;/p&gt;

&lt;p&gt;Custom Hooks start with the word "use" and can use other Hooks, such as useState and useEffect, to create the logic that our want to extract from our components.&lt;/p&gt;

&lt;p&gt;Here's a simple example, we use toggles a lot on the web, so this would be the logic to handle them&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const MyComponent = () =&amp;gt; {
  const [toggle, setToggle] = useState(false);

  const handleToggle = () =&amp;gt; {
    setToggle(!toggle);
  };

  return &amp;lt;button onClick={handleToggle}&amp;gt;Toggle {toggle ? "Off" : "On"}&amp;lt;/button&amp;gt;;
};

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

&lt;/div&gt;



&lt;p&gt;As you can see, we define a toggle state and a handle function to update the toggle. This code pattern will also apply if we have multiple toggles in the same project.&lt;/p&gt;

&lt;p&gt;Now here Custom Hook come into the picture&lt;br&gt;
&lt;/p&gt;

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

const useToggle = (initialValue) =&amp;gt; {
  const [toggle, setToggle] = useState(initialValue);

  const handleToggle = () =&amp;gt; {
    setToggle(!toggle);
  };

  return [toggle, handleToggle];
};

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

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// import useToggle hook 

const MyComponent = () =&amp;gt; {
  const [toggle, handleToggle] = useToggle(false);

  return &amp;lt;button onClick={handleToggle}&amp;gt;Toggle {toggle ? "Off" : "On"}&amp;lt;/button&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;useToggle&lt;/code&gt; hook contain the logic we defined in &lt;code&gt;MyComponent&lt;/code&gt; component and the interesting thing is that we can reuse this logic in every component with the help of hook.&lt;/p&gt;

&lt;p&gt;Let have look on another example&lt;/p&gt;

&lt;p&gt;When fetching data from an API we generally use state for loading, error and data. Here's what it would look like&lt;br&gt;
&lt;/p&gt;

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

const MyComponent = () =&amp;gt; {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() =&amp;gt; {
    async function fetchData() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/todos"
        );
        const data = await response.json();
        setData(data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  if (loading) {
    return &amp;lt;Loader /&amp;gt;;
  }

  if (error) {
    return &amp;lt;div&amp;gt;{error.message}&amp;lt;/div&amp;gt;;
  }

  return &amp;lt;div&amp;gt;{/* render data */}&amp;lt;/div&amp;gt;;
};

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

&lt;/div&gt;



&lt;p&gt;In the above example, we defined states for &lt;code&gt;data&lt;/code&gt;, &lt;code&gt;loading&lt;/code&gt;, and &lt;code&gt;error&lt;/code&gt; and used the &lt;code&gt;useEffect&lt;/code&gt; hook to get data from the API. We know that's a general pattern to get data from any API. Instead of writing all this stuff in every component, make a hook for this pattern (logic) so every component can fetch data api without writing anything new&lt;br&gt;
&lt;/p&gt;

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

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() =&amp;gt; {
    async function fetchData() {
      try {
        const response = await fetch(url);
        const data = await response.json();
        setData(data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    }

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;useFetch&lt;/code&gt; hook takes in a &lt;code&gt;url&lt;/code&gt; parameter and returns an object with three states: &lt;code&gt;data&lt;/code&gt;, &lt;code&gt;loading&lt;/code&gt;, and &lt;code&gt;error&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;useEffect&lt;/code&gt; hook is used to fetch the data from the specified url using the &lt;code&gt;fetch()&lt;/code&gt; API. If the fetch is successful, the data state is updated with the fetched data, and &lt;code&gt;loading&lt;/code&gt; is set to &lt;code&gt;false&lt;/code&gt;. If there's an error, the &lt;code&gt;error&lt;/code&gt; state is set to the error object, and &lt;code&gt;loading&lt;/code&gt; is set to &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The useFetch hook can be used in a component 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;// import useFetch hook

function MyComponent() {
  const { data, loading, error } = useFetch("https://jsonplaceholder.typicode.com/todos");

  if (loading) {
    return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  }

  if (error) {
    return &amp;lt;p&amp;gt;{error.message}&amp;lt;/p&amp;gt;;
  }

  return &amp;lt;div&amp;gt;{/* render data */}&amp;lt;/div&amp;gt;;
}

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

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;MyComponent&lt;/code&gt; component uses the &lt;code&gt;useFetch&lt;/code&gt; hook to fetch data from the specified URL. It checks the &lt;code&gt;loading&lt;/code&gt; and &lt;code&gt;error&lt;/code&gt; states to determine what to render while waiting for the data to load. Once the data is available, it can be rendered as desired.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Custom Hooks
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;First, they allow you to extract logic from your components and reuse it across multiple components, reducing the amount of code you need to write. This makes your code more readable and maintainable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Second, Custom Hooks allow you to separate concerns and create more modular code. By extracting logic into Custom Hooks, you can focus on the specific functionality of each component and avoid duplicating code across multiple components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, Custom Hooks allow you to create reusable code that can be shared across multiple projects. By creating Custom Hooks that encapsulate specific functionality, you can build a library of reusable components that can be used across different projects. This saves time and reduces the amount of code you need to write.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;In conclusion, Custom Hooks are a powerful tool in React that allow you to extract logic from your components and reuse it across multiple components. By using Custom Hooks, you can create more readable and maintainable code, reduce the amount of code you need to write, and create reusable code that can be shared across multiple projects.&lt;/p&gt;

&lt;p&gt;Did you create any Custom Hook in react? Let me know in comment👇🏻&lt;/p&gt;

</description>
      <category>frontend</category>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>How to use Code Splitting in ReactJS</title>
      <dc:creator>Rahul Khatri</dc:creator>
      <pubDate>Tue, 09 Aug 2022 17:02:05 +0000</pubDate>
      <link>https://forem.com/rahul72925/how-to-use-code-splitting-in-reactjs-2djj</link>
      <guid>https://forem.com/rahul72925/how-to-use-code-splitting-in-reactjs-2djj</guid>
      <description>&lt;p&gt;Hey Devs👋&lt;/p&gt;

&lt;p&gt;We all know that the ReactJS is very popular library in web application. We create a project small, medium and large size app. As our app grow the bundle of that app grow too. And especially when we use some third party modules. Which will accidentally make it so large that your app takes a long time to load. How fast user can interact with our app will directly proportional to user stay on our app.&lt;br&gt;
So we will learn one of the method to increase the performance of web app that is Code Splitting🔨. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Code Splitting in ReactJS?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Code Splitting is a feature which can create bundles that can be dynamically loaded at time. Basically this feature will split bundle into a smaller chunks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why we use Code Splitting?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is very interesting question 👍. Sometimes a single react component (&lt;code&gt;LargeComponent&lt;/code&gt;) get very large(large in having many child components) and we don't need all the children at a time😶.&lt;/p&gt;

&lt;p&gt;But these child components are still there. When we create a build for a project the complete chunk will be created for &lt;code&gt;LargeComponent&lt;/code&gt;.&lt;br&gt;
During the initial load of web page that complete chunk get download for rendering the &lt;code&gt;LargeComponent&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This will increase loading⌛ time of web page.&lt;br&gt;
To overcome this loading time we use Code Splitting. So that on initial load we will only get the code that required at that time 🙂.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GEkbkeki--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fduk3up5fokov8feikf3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GEkbkeki--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fduk3up5fokov8feikf3.png" alt="Image description" width="508" height="483"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see in above image there is a component called &lt;code&gt;LargeComponent&lt;/code&gt; which has three child component but on a initial loading we only need &lt;code&gt;Child1&lt;/code&gt; and &lt;code&gt;Child2&lt;/code&gt; but in a bundle there would be a complete chunk for &lt;code&gt;LargeComponent&lt;/code&gt;, &lt;code&gt;Child1&lt;/code&gt;, &lt;code&gt;Child2&lt;/code&gt; and &lt;code&gt;Child3&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vaWeAcoz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbh5wnsx7hl5ezyknuiv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vaWeAcoz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbh5wnsx7hl5ezyknuiv.png" alt="Image description" width="581" height="487"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After using Code Splitting the chunk for &lt;code&gt;Child3&lt;/code&gt; would be create separately from &lt;code&gt;LargeComponent&lt;/code&gt;, &lt;code&gt;Child1&lt;/code&gt; and &lt;code&gt;Child2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to use Code Spitting?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;React.lazy&lt;/code&gt;😴 function come in the picture to make the component lazy. The &lt;code&gt;React.lazy&lt;/code&gt; function lets you render a dynamic import as a regular component&lt;/p&gt;

&lt;p&gt;Before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Child3 from './Child3';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Child3 = React.lazy(() =&amp;gt; import('./Child3'));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will automatically load the bundle containing the &lt;code&gt;Child3&lt;/code&gt; when this component is first rendered.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;React.lazy&lt;/code&gt; takes a function that must call a dynamic &lt;code&gt;import()&lt;/code&gt;. This must return a Promise which resolves to a module with a default export containing a React component.&lt;/p&gt;

&lt;p&gt;The lazy component should then be rendered inside a &lt;code&gt;Suspense&lt;/code&gt; component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Suspense } from 'react';
import Child1 from './Child1';
import Child2 from './Child2';

const Child3 = React.lazy(() =&amp;gt; import('./OtherComponent'));

function ParentComponent() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Child1/&amp;gt;
      &amp;lt;Child2/&amp;gt;
      &amp;lt;Suspense fallback={&amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;}&amp;gt;
        &amp;lt;Child3/&amp;gt;
      &amp;lt;/Suspense&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see in above code &lt;code&gt;Child1&lt;/code&gt; and &lt;code&gt;Child2&lt;/code&gt; components are import directly. But the &lt;code&gt;Child3&lt;/code&gt; component import using &lt;code&gt;React.lazy&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The fallback prop accepts any React elements that you want to render while waiting for the &lt;code&gt;Child3&lt;/code&gt; component to load. &lt;/p&gt;

&lt;p&gt;This is the simplest implementation for code-splitting in ReactJS.&lt;/p&gt;

&lt;p&gt;Hope🤞🏻 you understand the concept of Code Splitting🙂.&lt;/p&gt;

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