<?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: Ruhul Amin</title>
    <description>The latest articles on Forem by Ruhul Amin (@ruhulamin77).</description>
    <link>https://forem.com/ruhulamin77</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%2F782605%2F63ab5a73-17fd-4a06-9845-ccdacfeb1386.jpeg</url>
      <title>Forem: Ruhul Amin</title>
      <link>https://forem.com/ruhulamin77</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ruhulamin77"/>
    <language>en</language>
    <item>
      <title>What is Unit Testing? Why Unit Testing is Important?</title>
      <dc:creator>Ruhul Amin</dc:creator>
      <pubDate>Fri, 04 Mar 2022 18:57:15 +0000</pubDate>
      <link>https://forem.com/ruhulamin77/what-is-unit-testing-why-unit-testing-is-important-1lpm</link>
      <guid>https://forem.com/ruhulamin77/what-is-unit-testing-why-unit-testing-is-important-1lpm</guid>
      <description>&lt;h2&gt;
  
  
  What is Unit Testing?
&lt;/h2&gt;

&lt;p&gt;Unit Testing is a type of software testing where individual units or components of software are tested. The purpose is to verify that each unit of the software code works as expected. Units are tested by developers during the development (coding phase) of an application. The unit isolates a section of test code and verifies its accuracy. A unit can be an individual function, method, method, module or object.&lt;/p&gt;

&lt;p&gt;The main aim is to isolate each unit of the system to identify, analyze and fix the defects.&lt;/p&gt;

&lt;p&gt;Coding is an important step in software development. So before doing this coding, the requirements are collected and analyzed, the architecture is designed, the platform, tools and programming language are decided. Then if the project gets bigger, coding is started by going through some more steps (like class and interaction design). Now an important thing when writing code is unit testing where different units are tested. Now what does the unit mean? A module can be considered as a single, interface can be considered as a unit, class can be considered as a unit, and function can also be considered as a single. I will now talk about writing test code with a single function. When we write big programs, we write each task into a separate function and one function will do only one task. If it is ever seen that a function is doing more than one thing, then it is necessary to break down the function and write smaller functions. So this function is the smallest unit.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qu60NsMe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ofhjs54s0ka7x07gvtx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qu60NsMe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ofhjs54s0ka7x07gvtx.jpg" alt="Unit Testing Advantages" width="880" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Unit Testing - Advantages:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Reduces Defects in the Newly developed features or reduces bugs when changing the existing functionality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unit Testing will reduce cost as defects are captured at an early stage.&lt;br&gt;
It improves design and allows better code refactoring.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Improves design and allows better refactoring of code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unit Tests, when integrated with build gives the quality of the build as well.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to do unit test?
&lt;/h2&gt;

&lt;p&gt;After writing the function, you have to write another function in a separate file for that function which will call that function through different input parameters. Then we have to compare the output to see if the output we are expecting and the output the function is giving are equal. Diameter, our unit became test. Different packages have been developed to facilitate unit testing in all programming languages ​​prevalent in the industry. Although the unit can be tested without using these packages.&lt;/p&gt;

&lt;h2&gt;
  
  
  Unit Testing LifeCyle:
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cG-eCwcU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hsa5mo1oxadbjhhcq7v.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cG-eCwcU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hsa5mo1oxadbjhhcq7v.jpg" alt="Unit Testing LifeCyle" width="462" height="479"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Unit Testing Techniques:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Black Box Testing - Using which the user interface, input and output are tested.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;White Box Testing - used to test each one of those functions behaviour is tested.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Gray Box Testing - Used to execute tests, risks and assessment methods.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>unittesting</category>
    </item>
    <item>
      <title>What is Redux? Why we should use it?</title>
      <dc:creator>Ruhul Amin</dc:creator>
      <pubDate>Fri, 25 Feb 2022 11:55:19 +0000</pubDate>
      <link>https://forem.com/ruhulamin77/what-is-redux-why-we-should-use-it-how-to-use-redux-in-a-react-project-bma</link>
      <guid>https://forem.com/ruhulamin77/what-is-redux-why-we-should-use-it-how-to-use-redux-in-a-react-project-bma</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is Redux&lt;/strong&gt;: Redux is a state management library that manages our application's all data and states. It is mostly used as a state management tool with React, Although we are discussing the use of Redax with React here, it is not the only one that can be used with React. We can use Redux in Angular, Vue, Vanila js if we want.&lt;/p&gt;

&lt;p&gt;By now we understand that Redux is mainly used to manage the application state. So let's take a look at the state at a glance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;State&lt;/strong&gt; is basically an object that contains specific information or data of a component. Since everything in the React is a component, when we work with the component state of the React, we need to transfer data from different component states to another component. Then we can manage the state by sending data through "Props".&lt;/p&gt;

&lt;h2&gt;
  
  
  Why we should use Redux:
&lt;/h2&gt;

&lt;p&gt;Suppose we have a lot of child components inside a parent. Now we want to change from one child component to another child component, so how do we do that? Let's look at the diagram below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--e2RSqgDL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/techdiary-dev/image/upload/c_scale%2Cf_auto%2Cq_auto/v1/techdiary-article-assets/cxxbsryeor4q7fazj4gt" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--e2RSqgDL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/techdiary-dev/image/upload/c_scale%2Cf_auto%2Cq_auto/v1/techdiary-article-assets/cxxbsryeor4q7fazj4gt" alt="component example" width="880" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we do not use Redux then we need to do props drilling to send data from one child component to another.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Prop drilling:&lt;/strong&gt; Reacts data flow system is unidirectional. When we need to pass data from one component to another component of a tree need to use the prop drilling process. In this process, props are passed from one component to another component that does not need the data but only helps in passing it through the tree. It’s called prop drilling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why we should avoid prop drilling?
&lt;/h2&gt;

&lt;p&gt;React is a very popular JavaScript library. The reason is that it is easy to implement and its great performance in a single-page application. But one of the biggest obstacles developers face when working with the library is components re-rendering excessively, which slows down the application performance. And component re-rendering is especially damaging when developers need components to communicate with each other in a process known as prop drilling. &lt;br&gt;
That is why we should avoid prop drilling, And the Redux will help us to get rid of this problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RE5Hoz3C--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://qph.fs.quoracdn.net/main-qimg-efd97474733f1fb58c76b37ba1bbd5fd-pjlq" alt="prop drilling" width="602" height="304"&gt;
&lt;/h2&gt;

&lt;p&gt;Now let us know about the hook of Redux. Redux basically stands on three concepts&lt;/p&gt;

&lt;p&gt;1.Store: Redux saves all the data of the application in one place and that is called Store&lt;/p&gt;

&lt;p&gt;2.Reducer: Redux will not allow changes directly to this store. Redux has to be told in advance what changes need to be made in the store if this happens.&lt;/p&gt;

&lt;p&gt;3.Action: And the message that needs to be sent to Redux to tell 'what happened' is Action.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IWdWfUP---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/techdiary-dev/image/upload/c_scale%2Cf_auto%2Cq_auto/v1/techdiary-article-assets/x6dwfac6naz4r9oezijy" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IWdWfUP---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/techdiary-dev/image/upload/c_scale%2Cf_auto%2Cq_auto/v1/techdiary-article-assets/x6dwfac6naz4r9oezijy" alt="react-redux" width="880" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>redux</category>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>What is CRUD Operation? How to Build CRUD Operations using React, Node, Express, and MongoDB?</title>
      <dc:creator>Ruhul Amin</dc:creator>
      <pubDate>Thu, 30 Dec 2021 10:47:34 +0000</pubDate>
      <link>https://forem.com/ruhulamin77/what-is-crud-operation-how-to-build-crud-operations-in-react-2k8f</link>
      <guid>https://forem.com/ruhulamin77/what-is-crud-operation-how-to-build-crud-operations-in-react-2k8f</guid>
      <description>&lt;h3&gt;
  
  
  CRUD:
&lt;/h3&gt;

&lt;p&gt;CRUD stands for Create, Read, Update, and Delete. CRUD typically refers to operations performed in a database. When an application is connected to a database, it adds data to the database, reads the data, updates any data can delete the data is called CRUD operation.&lt;/p&gt;

&lt;p&gt;Create — To insert any record into the database.&lt;br&gt;
Read — To retrieve records from the database.&lt;br&gt;
Update — To update a record in the database.&lt;br&gt;
Delete — To delete a record in the database&lt;/p&gt;
&lt;h2&gt;
  
  
  How to Build your CRUD Application:
&lt;/h2&gt;

&lt;p&gt;To create a CRUD operation first of all we need to create a react application. To create your React application, type&lt;code&gt;npx create-react-app &amp;lt;Your app name&amp;gt;&lt;/code&gt; in your terminal.&lt;/p&gt;

&lt;p&gt;You'll see that the packages are being installed. After creating this react project go to the project folder and open it, then open the terminal and command &lt;code&gt;npm start&lt;/code&gt;.&lt;br&gt;
Now you will see the default React template, like this:&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%2Fb06ke6kcecvwpfjhjfd3.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%2Fb06ke6kcecvwpfjhjfd3.png" alt="react default opening page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That means you successfully created a react application. &lt;/p&gt;

&lt;p&gt;Now we will go to your code editor and open the app.js file You will see a default boilerplate like this&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%2Fa5uprm3xfn3ak4od915m.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%2Fa5uprm3xfn3ak4od915m.png" alt="react app.js default boilerplate"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we need to create another project for the server. Before installing the server environment you must install node.js software on your computer.&lt;br&gt;
Now you can create a directory on your computer for the server, and open the directory in your terminal. Now you can create a server following steps.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;npm init -y &lt;/li&gt;
&lt;li&gt;Npm install express cors mongodb dotenv nodemon&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Insert the 2 following lines in your scripts property in your package.json file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "start": "node index.js",
    "start-dev": "nodemon index.js"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now open the project create a file named index.js and insert other necessary things.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { MongoClient } = require("mongodb");
require("dotenv").config();
const cors = require("cors");
const ObjectId = require("mongodb").ObjectId;
const app = express();
const port = process.env.PORT || 5000;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Must Use middleware in your &lt;code&gt;index.js&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(cors());
app.use(express.json());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then create your MongoDB cluster and input your &lt;code&gt;.env&lt;/code&gt; file and use it on your &lt;code&gt;index.js&lt;/code&gt; 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;const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.qu1uq.mongodb.net/myFirstDatabase?retryWrites=true&amp;amp;w=majority`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we create a function like the following code and create a database and connect with the database. write everything in the try block.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function run() {
  try {
await client.connect();
    const database = client.db("modernFurniture");
    const productsCollection = database.collection("products");
    const ordersCollection = database.collection("orders");
    const usersCollection = database.collection("users");
    const reviewsCollection = database.collection("reviews");

  } finally {
    // await client.close();
  }
}
run().catch(console.dir);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Let’s start CRUD Operations:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Create Operation:
&lt;/h3&gt;

&lt;p&gt;Now we create an HTML input form for getting some data and send it to the server for the Create operation.&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%2Fyh37bwv76uk7ww5j24o2.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%2Fyh37bwv76uk7ww5j24o2.png" alt="UI input form"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We use Axios and react hook form to send data to the server. For installing Axios write command on your terminal &lt;code&gt;npm i axios&lt;/code&gt;,  and for install react hook form &lt;code&gt;npm install react-hook-form&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 AddProduct = () =&amp;gt; {
  const { register, handleSubmit, reset } = useForm();
  const onSubmit = (data) =&amp;gt; {
    axios
   .post("http://localhost:5000/products", data)
      .then((res) =&amp;gt; {
        “Do something”        }
      });
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we create a post API on the node server to create data into the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   app.post("/products", async (req, res) =&amp;gt; {
      const product = req.body;
      const result = await productsCollection.insertOne(product);
      res.json(result);
    });

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

&lt;/div&gt;






&lt;h3&gt;
  
  
  Read Operation:
&lt;/h3&gt;

&lt;p&gt;Now we create a component on our client-side and send a request to the server for getting all data to show our browser. And when the server responds then stores the data in a state. And we can show data on the UI.&lt;/p&gt;

&lt;p&gt;Create a get request to get data from the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const [products, setProducts] = useState([]);
  useEffect(() =&amp;gt; {
    fetch("http://localhost:5000/products")
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; setProducts(data));
  }, []);

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

&lt;/div&gt;



&lt;p&gt;Sending data to the browser from the server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   // GET API
    app.get("/products", async (req, res) =&amp;gt; {
      const cursor = productsCollection.find({});
      const products = await cursor.toArray();
      res.json(products);
    });

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

&lt;/div&gt;






&lt;h3&gt;
  
  
  Update Operation:
&lt;/h3&gt;

&lt;p&gt;If further need to update the existing data then we use to update operation. First, we create an update request on our client-side with the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const user = { email };
    fetch("http://localhost:5000/users/admin", {
      method: "PUT",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(user),
    })
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; {
        "do something";
      });

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

&lt;/div&gt;



&lt;p&gt;Then the response from the server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   // make a admin user
    app.put("/users/admin", async (req, res) =&amp;gt; {
      const user = req.body;
      const filter = { email: user.email };
      const updateDoc = { $set: { role: "Admin" } };
      const result = await usersCollection.updateOne(filter, updateDoc);
      res.json(result);
    });

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

&lt;/div&gt;



&lt;p&gt;We make the normal user to an admin user use that above code.&lt;/p&gt;




&lt;h3&gt;
  
  
  Delete Operation:
&lt;/h3&gt;

&lt;p&gt;When we need to delete any data from the database then we use the delete operation. There we want to delete a customer order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const url = `http://localhost:5000/orders/${id}`;
        fetch(url, {
          method: "DELETE",
        })
          .then((res) =&amp;gt; res.json())
          .then((data) =&amp;gt; {
            if (data.deletedCount &amp;gt; 0) {
             alert("Deleted!", "Your order has been deleted.", "success");
            }
          });

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

&lt;/div&gt;



&lt;p&gt;Server response:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  // delete single order
    app.delete("/orders/:id", async (req, res) =&amp;gt; {
      const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const result = await ordersCollection.deleteOne(query);
      res.json(result);
    });

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

&lt;/div&gt;



&lt;p&gt;Now the server response and the order delete from ui and delete from the database also.&lt;/p&gt;

</description>
      <category>crud</category>
      <category>react</category>
      <category>nore</category>
      <category>mongodb</category>
    </item>
    <item>
      <title>What is context API? why we should use it? How to use it in react?</title>
      <dc:creator>Ruhul Amin</dc:creator>
      <pubDate>Thu, 30 Dec 2021 04:55:40 +0000</pubDate>
      <link>https://forem.com/ruhulamin77/what-is-context-api-why-we-should-use-it-how-does-it-work-418</link>
      <guid>https://forem.com/ruhulamin77/what-is-context-api-why-we-should-use-it-how-does-it-work-418</guid>
      <description>&lt;p&gt;&lt;strong&gt;Context API:&lt;/strong&gt; The Context API is a React structure that allows passing data from one component to another component without prop drilling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why we should use it?
&lt;/h2&gt;

&lt;p&gt;Well, before we know why context should be used, we need to know what is a component and what is props drilling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Component:&lt;/strong&gt; When our application becomes too large, it becomes very difficult to manage that application. To make the application easier to manage, we break it down into smaller sections, that is called components. Reusability is one of the biggest features of creating components.&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%2F95m0xqy3snbib9cs31xj.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%2F95m0xqy3snbib9cs31xj.png" alt="component example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prop drilling:&lt;/strong&gt; Reacts data flow system is unidirectional. When we need to pass data from one component to another component of a tree need to use the prop drilling process. In this process, props are passed from one component to another component that does not need the data but only helps in passing it through the tree. It’s called prop drilling.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why we should avoid prop drilling?
&lt;/h2&gt;

&lt;p&gt;React is a very popular JavaScript library. The reason is that it is easy to implement and its great performance in a single-page application. But one of the biggest obstacles developers face when working with the library is components re-rendering excessively, which slows down the application performance. And component re-rendering is especially damaging when developers need components to communicate with each other in a process known as prop drilling. &lt;br&gt;
That is why we should avoid prop drilling, And the context API will help us to get rid of this problem.&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%2Fpa1wyrkq15vosthjxged.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%2Fpa1wyrkq15vosthjxged.png" alt="prop drilling"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  How to use it in react?
&lt;/h2&gt;

&lt;p&gt;First of all, in our application, we need to import a &lt;code&gt;createContext()&lt;/code&gt; function from &lt;code&gt;react&lt;/code&gt;, and create a context. Then export it, So that it can be used by other components. And through a provider, we will pass in all the data as value.&lt;/p&gt;

&lt;p&gt;Then we will use all other components as &lt;code&gt;children&lt;/code&gt;of this context so that every component can use the data.&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, { createContext } from "react";
import useFirebase from "../../hooks/useFirebase";
export const AuthContext = createContext();
const AuthProvider = ({ children }) =&amp;gt; {
  const allContexts = useFirebase();
  return (
    &amp;lt;AuthContext.Provider value={allContexts}&amp;gt;
      {children}
    &amp;lt;/AuthContext.Provider&amp;gt;
  );
};
export default AuthProvider;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we will create another file and use the import &lt;code&gt;useContext()&lt;/code&gt; function from &lt;code&gt;react&lt;/code&gt;, and pass into the context data and &lt;code&gt;return&lt;/code&gt;it, so we can be used it by other components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext } from "react";
import { AuthContext } from "../contexts/AuthProvider/AuthProvider";
const useAuth = () =&amp;gt; {
  const auth = useContext(AuthContext);
  return auth;
};
export default useAuth;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And finally Wrapping all children by the AuthProvider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  return (
    &amp;lt;AuthProvider&amp;gt;
      &amp;lt;Booking /&amp;gt;
      &amp;lt;Dashboard /&amp;gt;
    &amp;lt;/AuthProvider&amp;gt;
  );
}
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can use all the data from any component without prop drilling.&lt;/p&gt;

</description>
      <category>react</category>
      <category>context</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
