<?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: Ahmad Mukahal</title>
    <description>The latest articles on Forem by Ahmad Mukahal (@ahmedm1999).</description>
    <link>https://forem.com/ahmedm1999</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%2F608513%2F09251fb6-32ad-442c-845a-e559d9f9b93b.jpeg</url>
      <title>Forem: Ahmad Mukahal</title>
      <link>https://forem.com/ahmedm1999</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ahmedm1999"/>
    <language>en</language>
    <item>
      <title>LinkedList Implementation of the most critical methods using Java generics.</title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Sun, 10 Jul 2022 13:31:30 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/linkedlist-implementation-of-the-most-critical-methods-using-java-generics-4cff</link>
      <guid>https://forem.com/ahmedm1999/linkedlist-implementation-of-the-most-critical-methods-using-java-generics-4cff</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Hi guys!&lt;br&gt;
In this post, I will explain the LinkedList data structure Briefly and try to implement its most critical methods using Java programming language. So, you will know how it works in the memory and how it implements its main methods.&lt;br&gt;
We will implement it using Java's generics, so, we can store any type of data on our LinkedList.&lt;/p&gt;
&lt;h2&gt;
  
  
  Linked List
&lt;/h2&gt;

&lt;p&gt;A Linked List Is Linear Data Structure that store values in nodes. Each node contains two parts: &lt;strong&gt;Data&lt;/strong&gt; and &lt;strong&gt;Reference for the next node&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Linked list is the second most-used data structure after array. Following are the important terms to understand the concept of Linked List.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Node: Each node of a linked list can store data called an &lt;br&gt;
    element.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next: Each node of a linked list contains a link(Reference) to &lt;br&gt;
     the next node is called Next.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Head: Each LinkedList contains a head that points to the first &lt;br&gt;
    node in the list and to NULL if the list is empty.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This image will illustrate the Linked List concepts:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--52OoxraQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfvxaev8dlzzkih4e3fr.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--52OoxraQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfvxaev8dlzzkih4e3fr.jpg" alt="LinkedList" width="600" height="109"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Basic Operations
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Insertion: Adds an element to the LinkedList.&lt;/li&gt;
&lt;li&gt;Deletion: Delete an element from the LinkedList.&lt;/li&gt;
&lt;li&gt;Get: Get the element's data specified in an array-like index (0-length)&lt;/li&gt;
&lt;li&gt;Clear: Clear the LinkedList and make it empty.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Now we will start implementing all these operations in Java from scratch.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Node class
&lt;/h2&gt;

&lt;p&gt;First, we will define the Node class that contains two parts: data and next&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node&amp;lt;T&amp;gt; {
        T nodeData;
    Node&amp;lt;T&amp;gt; next; // points to the next node

// Constructor to instantiate the node object with default values
        Node(T data) {
       this.nodeData = data;
       next = null;
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  LinkedList class
&lt;/h2&gt;

&lt;p&gt;Second, we will define the LinkedList class that contains:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;head: Object of type Node.&lt;/li&gt;
&lt;li&gt;length: An integer value (length of the list).
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MyLinkedList&amp;lt;T&amp;gt; {
    Node&amp;lt;T&amp;gt; head;
    private int length = 0;
// Constructor 
MyLinkedList() {
        this.head = null;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Now we will start implementing the basic operations&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Insertion
&lt;/h2&gt;

&lt;p&gt;Insert has two methods:&lt;br&gt;
First &lt;code&gt;public final void add(T data)&lt;/code&gt; insert to the end of the list&lt;br&gt;
And &lt;br&gt;
&lt;code&gt;public final void add(T data, int pos)&lt;/code&gt; Inserts in Specific Position.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Insert on the end of the LinkedList
    // Complexity: O(n)
    public final void add(T data) {
        Node&amp;lt;T&amp;gt; newNode = new Node&amp;lt;T&amp;gt;(data);

        if(this.head == null) {
            this.head = newNode;
            newNode.next = null;
        } else {
            Node&amp;lt;T&amp;gt; pointer = this.head;

            while (pointer.next != null) {
                pointer = pointer.next;
            } 

            pointer.next = newNode;  
            newNode.next = null;
        }
        this.length++;
    }
    // Insert in Specific Position
    // Complexity: O(n)
    public final void add(T data, int pos) {
        if(pos == 0) {
            this.addFirst(data);
            return;
        }
        if(pos &amp;lt; 0 || pos &amp;gt; this.length) {
            System.out.println("Error: Out of range");
        } else {
            Node&amp;lt;T&amp;gt; newNode = new Node&amp;lt;T&amp;gt;(data);
            Node&amp;lt;T&amp;gt; pointer = head;

            for(int i = 1; i &amp;lt; pos; i++) {
                pointer = pointer.next;
            }
            newNode.next = pointer.next;
            pointer.next = newNode;
            this.length++;
        }
    }

    // Insert First (begging of the list)
    public final void addFirst(T data) {

        Node&amp;lt;T&amp;gt; newNode = new Node&amp;lt;T&amp;gt;(data);

        newNode.next = head;
        head = newNode;
        this.length++;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Deletion
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Delete from last of LinkedList 
    // Complexity: O(n)
    public void remove() {
        if(isEmpty()) {
            System.out.println("Sorry, List is empty!!");
        } else if(this.length == 1) {
            head = null;
            System.out.println("Removed Successfully");
            this.length = 0;
        } else {
            Node&amp;lt;T&amp;gt; pointer = head;

            while(pointer.next.next != null) {
                pointer = pointer.next;
            }
            pointer.next = null;
            this.length--;
            System.out.println("Removed Successfully");
        }
    }
    // Remove LinkedList Element from specific position
    // Complexity: O(n)
    public void remove(int pos) {
        if(pos &amp;lt; 0 || pos &amp;gt;= length) {
            System.out.println("Error: Position is out of range");
        } else if (pos == length - 1) {
            remove();
        } else {
            if (pos == 0) {
                removeFirst();
                return;
            }
            Node&amp;lt;T&amp;gt; pointer = head;

            for(int i = 1; i &amp;lt; pos; i++) {
                pointer = pointer.next;
            }
            pointer.next = pointer.next.next;
            length--;
        }
    }
    // Remove the first element in the LinkedList
    public void removeFirst() {
        head = head.next;
        length--;
    }
    // Get LinkedList element's Data for specific Index
    // Complexity: O(n)
    public T get(int index) {
        if(index &amp;lt; 0 || index &amp;gt;= length) {
            return  null;
        }
        Node&amp;lt;T&amp;gt; pointer = head;
        for(int i = 0; i &amp;lt; index; i++) {
            pointer = pointer.next;
        }
        return pointer.nodeData;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Get
&lt;/h2&gt;

&lt;p&gt;This method returns the data contained by the node specified by the index parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Get LinkedList element's Data for specific Index
    // Complexity: O(n)
    public T get(int index) {
        if(index &amp;lt; 0 || index &amp;gt;= length) {
            return  null;
        }
        Node&amp;lt;T&amp;gt; pointer = head;
        for(int i = 0; i &amp;lt; index; i++) {
            pointer = pointer.next;
        }
        return pointer.nodeData;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Clear
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final void clear() {
        this.head = null;
        length = 0;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Additional methods
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Get LinkedList Length
    public int getLingth() {
        return this.length;
    }
    // Return true if the LinkedList is empty
    public boolean isEmpty() {
        if (this.length == 0) return true;
        return false;
    }

    // Convert LinkedList to string
    // Complexity: O(n)
    public String toString()
    {

        String S = "{ ";

        Node&amp;lt;T&amp;gt; X = head;

        if (X == null)
            return S + " }";

        while (X.next != null) {
            S += String.valueOf(X.nodeData) + " -&amp;gt; ";
            X = X.next;
        }

        S += String.valueOf(X.nodeData);
        return S + " }";
    }

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Print method
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Print all List elements
    // Complexity: O(n)
    public final void print() {
        Node&amp;lt;T&amp;gt; pointer = head;

        while (pointer != null) {
            System.out.println(pointer.nodeData);
            pointer = pointer.next;
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hope this post is helpful.&lt;/p&gt;

&lt;p&gt;I'm sorry if I made any mistakes, and thank you for reading.&lt;/p&gt;

&lt;p&gt;BR&lt;br&gt;
Ahmad Mukahal.&lt;/p&gt;

</description>
      <category>java</category>
      <category>linkedlist</category>
      <category>datastructures</category>
      <category>bigo</category>
    </item>
    <item>
      <title>Association in OOP</title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Sun, 29 May 2022 20:38:34 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/association-in-oop-174b</link>
      <guid>https://forem.com/ahmedm1999/association-in-oop-174b</guid>
      <description>&lt;p&gt;&lt;em&gt;Association&lt;/em&gt; in OOP is a connection or relation between two separate #classes that are set up through their #objects. Association relationship indicates how objects know each other and how they are using each other’s functionality. It can be one-to-one, one-to-many, many-to-one, and many-to-many.&lt;/p&gt;

&lt;p&gt;For example, a person can have only one passport. That is a “one-to-one” relationship between person class and passport class.&lt;br&gt;
 And so on;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;&lt;em&gt;- Two Forms of Association&lt;/em&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Composition and Aggregation are the two special forms of association, both of them have a "has-a" relationship. let's check them out:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1- Composition&lt;/strong&gt;&lt;br&gt;
It simply means that one large object contains the other smaller object. In other words, it’s part or member of the larger object.&lt;br&gt;
For example, a building (large object) #has rooms (smaller object).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2- Aggregation&lt;/strong&gt; &lt;br&gt;
Aggregation is also a “has-a” relationship, It is like a composition with Minor logical differences:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;em&gt;- *&lt;em&gt;Aggregation vs Composition *&lt;/em&gt;&lt;/em&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Dependency:&lt;/strong&gt; &lt;br&gt;
Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. For example: if the building is destroyed the room is destroyed but the building will still exist!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Type of association:&lt;/strong&gt;&lt;br&gt;
 Composition is a strong Association whereas Aggregation is called a weak Association.&lt;/p&gt;

</description>
      <category>oop</category>
      <category>java</category>
    </item>
    <item>
      <title>JavaScript factory functions and Object.create()</title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Fri, 14 Jan 2022 13:52:23 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/javascript-factory-functions-and-objectcreat-4kbi</link>
      <guid>https://forem.com/ahmedm1999/javascript-factory-functions-and-objectcreat-4kbi</guid>
      <description>&lt;p&gt;Do you know JavaScript factory function and its issues, and why we use Object.create() method instead?&lt;/p&gt;

&lt;p&gt;Hello 🖐,&lt;/p&gt;

&lt;p&gt;Factory functions in JS are any function that return an object. &lt;/p&gt;

&lt;p&gt;like this one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName() {
            return firstName + ' ' + lastName;
        }
    }
}
const person1 = createPerson("Ahmad", "Mukahal");
const person1 = createPerson("john", "Deo");

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

&lt;/div&gt;



&lt;p&gt;and so on...&lt;/p&gt;

&lt;p&gt;With the factory function, you create any number of the person objects you want without duplicating code.&lt;/p&gt;

&lt;p&gt;What if we have one thousand persons? It will store a thousand objects in the memory heap! and this is not an efficient way.&lt;/p&gt;

&lt;p&gt;Example: &lt;br&gt;
Each object will have a different address in the memory and every object will have the getFullName() method, Ooh no, I'm not DRY!!&lt;/p&gt;

&lt;p&gt;This is why the Object.create() method comes into play.&lt;/p&gt;

&lt;p&gt;The Object.create() method creates a new object using an existing object as the prototype of the new object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
firstName : "John",
lastName: "Deo",
getFullName() {
            return firstName + ' ' + lastName;
        }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;// Make prototype chain:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const me = Object.create(person);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so, now &lt;code&gt;me&lt;/code&gt; object has all properties and methods in person object, and it can hold its own props and methods and override props and methods as you want 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;console.log(me.firstName) // John
me.firstName = "Ahmad";
me.lastName = "Mukahal";
console.log(me.firstName) // Ahmad
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What efficient is that !!&lt;/p&gt;

&lt;p&gt;Hopefully enjoyed reading.&lt;/p&gt;

&lt;p&gt;Ahmad Mukahal 🌹&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>typescript</category>
    </item>
    <item>
      <title>JavaScript is a single threaded "Synchronous", What does that mean?!</title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Fri, 24 Dec 2021 13:48:00 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/javascript-is-a-single-threaded-synchronous-what-does-that-mean-271h</link>
      <guid>https://forem.com/ahmedm1999/javascript-is-a-single-threaded-synchronous-what-does-that-mean-271h</guid>
      <description>&lt;p&gt;Hello everyone, in this article I will give you the mean of &lt;strong&gt;single threaded javascript&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;First, let's talk about the &lt;strong&gt;JavaScript engine&lt;/strong&gt; in brief way.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;JavaScript engine&lt;/code&gt; is a software component that executes JavaScript code, Its consists of many steps and components to allow it perform it's tasks.&lt;/p&gt;

&lt;p&gt;The two main important things in this step are: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1-&lt;/strong&gt; We need to store and write information/data for our application (variables, objects, etc..).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2-&lt;/strong&gt; We need to keep track of what's happening to our code line by line.&lt;/p&gt;

&lt;p&gt;This is where a &lt;code&gt;Call stack&lt;/code&gt; and &lt;code&gt;Memory heap&lt;/code&gt; comes in.&lt;/p&gt;

&lt;p&gt;This image explain this two component in graphical way :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TJImUnvL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/766bridbz6pyjqjwr4u4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TJImUnvL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/766bridbz6pyjqjwr4u4.jpg" alt="Memory heap and call stack" width="524" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; Call stack: &lt;/p&gt;

&lt;p&gt;Help to know where we are in the code and to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.&lt;br&gt;
To know more about call stack and how it is work exactly, I recommend &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Call_stack"&gt;this tutorial&lt;/a&gt;  for you.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; Memory heap:&lt;/p&gt;

&lt;p&gt;The memory heap, also called the ‘heap’, is a section of unstructured memory that is used for the allocation of objects and variables, so it is where our variables and functions stores Briefly.&lt;br&gt;
To deep in heap from &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After that, back to our main subject, &lt;strong&gt;"Javascript is a single threaded programming language"&lt;/strong&gt; which means it has only one call stack that is used to execute the program, so one set of instructions is executed at a time, it's not doing multiple things.&lt;br&gt;
And because of that JavaScript is &lt;strong&gt;Synchronous&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So if you understand what is single threaded means, it's the same concept with Synchronous JavaScript &lt;strong&gt;"one thing at a time"&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This approach of programming lead to make many problems, so the direction now to use another way of JavaScript called &lt;strong&gt;"Asynchronous"&lt;/strong&gt; programming.&lt;br&gt;
I will make to it another article in the come in days.&lt;/p&gt;

&lt;p&gt;Hope you clearly understand this important concepts as a JavaScript developer! 🙌🌹 &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Ahmad Mukahal&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>angular</category>
      <category>vue</category>
    </item>
    <item>
      <title>Complete guides to React useReducer() Hook </title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Sun, 05 Sep 2021 13:51:44 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/complete-guides-to-react-usereducer-hook-5j7</link>
      <guid>https://forem.com/ahmedm1999/complete-guides-to-react-usereducer-hook-5j7</guid>
      <description>&lt;p&gt;&lt;code&gt;useReducer()&lt;/code&gt; is a React.js Hook which manage complex state in your application and update it based on the 'action' you send to.&lt;br&gt;
It's used as an alternative for &lt;code&gt;useState&lt;/code&gt; if you have a complex states or can be used both together according to your application requirements.&lt;br&gt;
It's very similar to &lt;code&gt;Redux&lt;/code&gt; if you want to not use a 3rd-party library.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h2&gt;First&lt;/h2&gt;

&lt;p&gt;You should import &lt;code&gt;useReducer&lt;/code&gt; from react js&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, { useReducer } from 'react';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;Second :&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;useReducer&lt;/code&gt; Hook accepts a reducer function, and an initial state.&lt;br&gt;
It's returns an array with 2 values:&lt;br&gt;
The first one is the &lt;code&gt;state&lt;/code&gt; value, and the second value is the &lt;code&gt;dispatch&lt;/code&gt; function which is used to trigger an action with the help of ES6 destructuring.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialState);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;initialState :&lt;/h5&gt;

&lt;p&gt;The initial state that we want to start working on it&lt;/p&gt;

&lt;h5&gt;reducer :&lt;/h5&gt;

&lt;p&gt;Which we'll use to manipulate our state.&lt;/p&gt;

&lt;h1&gt;Let's go with simple example&lt;/h1&gt;

&lt;p&gt;Let's say you're displaying some products in your app, and you want to :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add a product to the cart when user click on &lt;code&gt;add to cart&lt;/code&gt; button and list it in cart page.&lt;/li&gt;
&lt;li&gt;Remove the product from cart list if the user click on &lt;code&gt;remove from cart&lt;/code&gt; button.&lt;/li&gt;
&lt;li&gt;User can switch the application (dark/light mode)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Create &lt;code&gt;Reducer.js&lt;/code&gt; component to add our reducer in it.&lt;/em&gt;&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;Firstly, we will define the reducer function that will manipulate our state:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Reducer.js
const reducer = (state, action) =&amp;gt; {
  // reducer function accepts two arguments 
  /* 
   the first one is `state` which is going to be the state 
   before the update.
  */ 
  /* 
   the second one is `action` which is what are we trying to do.
  */ 
}

export default reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Second step, we will define the initial state object which contains our initial values :
&lt;p&gt;1- &lt;code&gt;cart&lt;/code&gt; array property which holds products user added to his/her cart.&lt;/p&gt;
&lt;p&gt;2- &lt;code&gt;mode&lt;/code&gt; property which holds the app mode and it's by default will be &lt;code&gt;light&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We'll put those in our file, but outside of the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Reducer.js
export const initialState = {
    cart: [],
    mode: 'light'
};

const reducer = (state, action) =&amp;gt; {
    switch (action.type) {
        case 'ADD_TO_CART':
            return {
                ...state,
                cart: [...state.cart, action.item]
            };

        case 'REMOVE_FROM_CART':
            const index = state.cart.findIndex(item =&amp;gt; action.id === item.id);
            let newCart = [...state.cart];
            if (index &amp;gt;= 0) {
                newCart.splice(index, 1);
            }

            if (newCart.length === 0) {
                return {
                    ...state,
                    cart: newCart,
                }
            } else {
                return {
                    ...state,
                    cart: newCart,
                }
            };
        case 'CHANGE_MODE':
            return {
                ...state,
                mode: action.mode
            }
        default: return state
    }

}

export default reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's imagine we have a &lt;code&gt;Product.js&lt;/code&gt; component that return a products to be displayed in your app.&lt;br&gt;
&lt;/p&gt;

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

function Product({ name, image }) {
    const addToCart= () =&amp;gt; {
        // some code
    }
    return (
        &amp;lt;div className="product"&amp;gt;
            &amp;lt;img src={`${image}`} /&amp;gt;
            &amp;lt;p&amp;gt;{name}&amp;lt;/p&amp;gt;
            &amp;lt;button onClick={addToCart}&amp;gt;add to cart&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

export default Product

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The fourth step, our reducer is all setup, now let's define then use it.
To be able to use the reducer function you must define it in everywhere you need like so:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useReducer} from 'react'
import reducer, {initialState} from './Reducer';

function Product({ name, image }) {
    const [state, dispatch] = useReducer(reducer, initialState) ;
    .
    .
    .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Firstly you need to import &lt;code&gt;useReducer&lt;/code&gt; from React, then import the &lt;code&gt;reducer&lt;/code&gt; and &lt;code&gt;initialState&lt;/code&gt; to be used.&lt;br&gt;
Now we will define our reducer using &lt;code&gt;useReducer()&lt;/code&gt; hook&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialState) ;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useReducer hook will return two things in an array: the state, and a dispatcher to update the state.&lt;/p&gt;

&lt;p&gt;We will grab those with array destructuring, similar to state and setState with the useState.&lt;/p&gt;

&lt;h2&gt;Dispatch actions :&lt;/h2&gt;

&lt;p&gt;Every time the user clicks on &lt;code&gt;add to cart&lt;/code&gt; button, &lt;code&gt;addToCart&lt;/code&gt; function will be called to &lt;strong&gt;dispatch&lt;/strong&gt; the action to the reducer function to do some changes in that state.&lt;br&gt;
So, the &lt;code&gt;addToCart&lt;/code&gt; function will contains 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 addToCart= () =&amp;gt; {
        dispatch({
            type: 'ADD_TO_CART',
            item: {
                image,
                name
            }
        })
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We sent the action name to the reducer function to know what kind of changes will be happened, in this case the action is &lt;code&gt;ADD_TO_CART&lt;/code&gt; action. Also we sent the item or the product which user need to add to the card to be added to the &lt;code&gt;state.cart&lt;/code&gt; array.&lt;/p&gt;

&lt;p&gt;So, the &lt;code&gt;Product.js&lt;/code&gt; component will be :&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, {useReducer} from 'react'
import reducer, {initialState} from './Reducer';

function Product({ name, image }) {
    const [state, dispatch] = useReducer(reducer, initialState) ;
    const addToCart= () =&amp;gt; {
        dispatch({
            type: 'ADD_TO_CART',
            item: {
                image,
                name
            }
        })
    }
    return (
        &amp;lt;div className="product"&amp;gt;
            &amp;lt;img src={`${image}`} /&amp;gt;
            &amp;lt;p&amp;gt;{name}&amp;lt;/p&amp;gt;
            &amp;lt;button onClick={addToCart}&amp;gt;add to cart&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

export default Product

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

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;We will be satisfied with ADD_TO_CART, others actions will be the same but with deferent functionality&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Accessing state&lt;/h2&gt;

&lt;p&gt;Now you can accessing the state and make on it anything you want like mapping cart array and so on.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;useReducer Hook is extremely useful when working on complex and different states depend on each other.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;useReducer is very similar to Redux if you want to not use a 3rd-party library or if it's only for a component or two.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hope this article helped you to understand useReducer hook what is exactly.&lt;/p&gt;

&lt;p&gt;Thanks for reading 🙌&lt;br&gt;
-Ahmad Mukahal&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>redux</category>
      <category>beginners</category>
    </item>
    <item>
      <title>React Context API - Why, How and When ? With full example.</title>
      <dc:creator>Ahmad Mukahal</dc:creator>
      <pubDate>Mon, 16 Aug 2021 10:11:00 +0000</pubDate>
      <link>https://forem.com/ahmedm1999/react-context-api-why-how-and-when-with-full-example-28d0</link>
      <guid>https://forem.com/ahmedm1999/react-context-api-why-how-and-when-with-full-example-28d0</guid>
      <description>&lt;p&gt;Hello everybody, in this article we are gonna go deeper and deeper in some React more complex topics like state management, let's get going ... &lt;br&gt;
&lt;br&gt; &lt;br&gt;
One of the most important features about React is that we have a lot of different ways to solve any problem we face. And one of this problems we might have is 'State Management' issues in React. &lt;br&gt;
&lt;br&gt;&lt;br&gt;
First, let's say we building an e-commerce app, so we want to display a list of products and we want to have a navigation bar in a head, so let's make a component with the products list first &lt;code&gt;ProductList.js&lt;/code&gt;.&lt;br&gt;
&lt;br&gt;&lt;br&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%2F78zvkgj7o1frdpsdkvxx.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%2F78zvkgj7o1frdpsdkvxx.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
So I'm just created a new React component with &lt;strong&gt;ProductList.js&lt;/strong&gt; name.&lt;br&gt;
&lt;br&gt;&lt;br&gt;
Now, we need a &lt;code&gt;state&lt;/code&gt; Hook to store our products list array on objects form, I just want tow properties in each product object, it's &lt;code&gt;productName&lt;/code&gt; and &lt;code&gt;productIamge&lt;/code&gt;. &lt;br&gt;&lt;br&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%2Fq7ypw9ofp3f7mwh37vek.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%2Fq7ypw9ofp3f7mwh37vek.png" alt="Alt Text"&gt;&lt;/a&gt; &lt;br&gt;&lt;br&gt;
So now, I just want to render this products as a cards using some &lt;code&gt;CSS&lt;/code&gt; and &lt;code&gt;products.map()&lt;/code&gt; method so you can imagen this cards listed in a screen like so. &lt;br&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%2F8n803zq9zkvp9ugf2vxq.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%2F8n803zq9zkvp9ugf2vxq.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
We know that one of the concepts of React is you can split your app into components for reusability purposes and to be more maintainable code. So we want to make another component called &lt;strong&gt;Product.js&lt;/strong&gt; that receives product image and name as a &lt;strong&gt;prop&lt;/strong&gt; and return this products one by one to be rendered :&lt;br&gt;&lt;br&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%2Fkhs4e5wlmpabrxhv9hf8.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%2Fkhs4e5wlmpabrxhv9hf8.png" alt="Alt Text"&gt;&lt;/a&gt; &lt;br&gt;&lt;br&gt;
and calls this component inside &lt;code&gt;products.map()&lt;/code&gt; method in &lt;code&gt;ProductList.js&lt;/code&gt; like so : &lt;br&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%2Fkifya5cx696ijtnqrry0.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%2Fkifya5cx696ijtnqrry0.png" alt="Render products one by one from ProductList.js coponent"&gt;&lt;/a&gt; &lt;br&gt;&lt;/p&gt;

&lt;p&gt;Now, I want create a navbar in a top of our app that contain my name and the number of products I have in my list, so I will create &lt;code&gt;Nav.js&lt;/code&gt; component and render it in our &lt;code&gt;App.js&lt;/code&gt; component with some &lt;code&gt;css&lt;/code&gt; ..&lt;br&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%2Ff7r6qw8kglzf3w9ncqf6.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%2Ff7r6qw8kglzf3w9ncqf6.png" alt="Alt Text"&gt;&lt;/a&gt; &lt;br&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%2Fj8odfoapxhh9hj73dzoy.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%2Fj8odfoapxhh9hj73dzoy.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
Ok, everything is fine ..&lt;br&gt;
Now I want to render the number of products I have in the &lt;code&gt;ProductList.js&lt;/code&gt; to &lt;code&gt;Nav.js&lt;/code&gt; component &lt;strong&gt;and I can't do that !!&lt;/strong&gt; &lt;br&gt; Because I have rendered the &lt;code&gt;Nav&lt;/code&gt; component in the &lt;code&gt;App.js&lt;/code&gt; that not have an access to our state in &lt;code&gt;ProductLis.js&lt;/code&gt; component and the only way to do that is to passing the state &lt;code&gt;length&lt;/code&gt; down to &lt;strong&gt;props&lt;/strong&gt; ..&lt;br&gt;
The only way is we will render the &lt;code&gt;Nav.js&lt;/code&gt; component in our &lt;code&gt;ProductList.js&lt;/code&gt; component like so :&lt;br&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%2Fe7wjgveukrje795w2t90.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%2Fe7wjgveukrje795w2t90.png" alt="Rendering Nav.js in ProductList.js"&gt;&lt;/a&gt;&lt;br&gt;
But I don't want to render the &lt;code&gt;Nav.js&lt;/code&gt; here ! it's make no sense to have the navbar in my &lt;code&gt;ProductList.js&lt;/code&gt; so we will fix this in take the &lt;code&gt;state&lt;/code&gt; from &lt;code&gt;ProductList.js&lt;/code&gt;, cut it, and move it up to &lt;code&gt;App.js&lt;/code&gt; (the parent component) like so :&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%2Fje7f1vhkst91xiqmcmtu.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%2Fje7f1vhkst91xiqmcmtu.png" alt="Move the state to App.js parent component"&gt;&lt;/a&gt;&lt;br&gt;
In this way, now we can pass down the products to our navbar and products list, so we can pass it to any component we want.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But, the problem with that&lt;/strong&gt; we will have a lot of state in our &lt;code&gt;App.js&lt;/code&gt; component that doesn't belong to &lt;code&gt;App.js&lt;/code&gt; component, so this will work, but will be a bit difficult, &lt;strong&gt;Why?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because if we also want to pass down props we're gonna have &lt;strong&gt;Prop Drill&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Prop Drilling ?&lt;/strong&gt;&lt;br&gt;
It's basically means we will &lt;strong&gt;pass props down from component to components to components to components until we arrives the component we want..&lt;/strong&gt;&lt;br&gt;
So we would have keep passing the props over and over and over again..!&lt;br&gt;&lt;br&gt;
So in our example, we will passing the &lt;code&gt;products&lt;/code&gt; state :&lt;br&gt;
1- from &lt;code&gt;App.js&lt;/code&gt; to &lt;code&gt;ProductList.js&lt;/code&gt; component&lt;br&gt;
2- from &lt;code&gt;ProductList.js&lt;/code&gt; to &lt;code&gt;Product.js&lt;/code&gt; component&lt;br&gt;
3- from &lt;code&gt;App.js&lt;/code&gt; to &lt;code&gt;Nav.js&lt;/code&gt; component&lt;br&gt;
4- and more and more ..&lt;br&gt;&lt;br&gt;
It's a big problem that's effects the app performance and make it hard to read, understand and to be edited.&lt;/p&gt;

&lt;p&gt;So we will go back and pass everything back up so the way we were in the first place.&lt;br&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%2F1ykt2p6fzz8e68ubbtf9.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%2F1ykt2p6fzz8e68ubbtf9.png" alt="Back to our first stage"&gt;&lt;/a&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
So The way to fix the "Prop drilling issue" is with &lt;strong&gt;State Management&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;React offers a way to manage our state which is called &lt;strong&gt;context&lt;/strong&gt;. The way this works is rather than adding the state in particular component, we can separate that logic into one component called &lt;code&gt;Context Component&lt;/code&gt; that's holds all information, then with the context we can pass it down to which every component we want without going to props.&lt;br&gt;&lt;/p&gt;

&lt;p&gt;So let's take a look how we can do that, I will create a new file and I gonna call this &lt;code&gt;ProductsContext.js&lt;/code&gt;.&lt;br&gt;
Inside this file I gonna &lt;code&gt;import React from 'react'&lt;/code&gt;&lt;br&gt;
and make a new component &lt;code&gt;ProductsProvider&lt;/code&gt; as ES6 function component and &lt;code&gt;export&lt;/code&gt; it but not default because I want export tow different things from this component like so : (I will explain everything don't worry)&lt;br&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%2F9hgqqv629wfo8rpctk9m.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%2F9hgqqv629wfo8rpctk9m.png" alt="make a products provider component"&gt;&lt;/a&gt;&lt;br&gt;
Now, what we want to do ? &lt;/p&gt;

&lt;p&gt;&lt;em&gt;First step :&lt;/em&gt;&lt;br&gt;
I will move our &lt;code&gt;products state&lt;/code&gt; from &lt;code&gt;ProductList.js&lt;/code&gt; component to &lt;code&gt;ProductsProvider&lt;/code&gt; component and import &lt;code&gt;useState&lt;/code&gt; in it like this :&lt;br&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%2F9bex2vsgsrj7p9ygxytm.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%2F9bex2vsgsrj7p9ygxytm.png" alt="Moving our state"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
&lt;em&gt;Second step :&lt;/em&gt;&lt;br&gt;
Now, we want create our &lt;strong&gt;context&lt;/strong&gt;, the first step to create any React &lt;strong&gt;context&lt;/strong&gt; is with &lt;code&gt;createContext&lt;/code&gt; function from react:&lt;/p&gt;

&lt;h1&gt;
  
  
  createContext
&lt;/h1&gt;

&lt;p&gt;To start with the Context API, the first thing we need to do is create a context using the createContext function after we import it from React like so :&lt;br&gt;
&lt;code&gt;import {createContext} from 'react' ;&lt;/code&gt;.&lt;br&gt;
The second thing is to create our context like so: &lt;br&gt;
&lt;code&gt;export const ProductsContext = createContext(initialValue);&lt;/code&gt;&lt;br&gt;&lt;br&gt;
** The createContext function accepts an initial value, but this initial value is &lt;strong&gt;&lt;em&gt;not&lt;/em&gt;&lt;/strong&gt; required.&lt;br&gt;&lt;br&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%2Fudod5xuo2wabvvg7zoey.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%2Fudod5xuo2wabvvg7zoey.png" alt="createContext"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
After creating the context, our context now has &lt;strong&gt;&lt;em&gt;tow&lt;/em&gt;&lt;/strong&gt; React components to be used: &lt;em&gt;Provider&lt;/em&gt; and &lt;em&gt;Consumer&lt;/em&gt;.&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Provider :&lt;/strong&gt;&lt;br&gt;
The Provider component is going to be used to wrap the components that are going to have access to our context, such as &lt;code&gt;Product.js&lt;/code&gt; and &lt;code&gt;Nav.js&lt;/code&gt; who are the &lt;code&gt;children&lt;/code&gt; of &lt;code&gt;App.js&lt;/code&gt; component in our example.&lt;br&gt;
So, we will import our &lt;code&gt;productsProvider&lt;/code&gt; in &lt;code&gt;App.js&lt;/code&gt; component first, then we will use it to wrap other components we want to give an access to the context like so :&lt;br&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%2Ffs7zwgbkrb0tgx6qk0a9.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%2Ffs7zwgbkrb0tgx6qk0a9.png" alt="Wrap components inside our context"&gt;&lt;/a&gt;&lt;br&gt;
So now everything in the &lt;code&gt;productsProvider&lt;/code&gt; are easily accessible for &lt;code&gt;Product.js&lt;/code&gt; and &lt;code&gt;Nav.js&lt;/code&gt;. &lt;br&gt;&lt;br&gt;
Now, we will go back to our ContextProvider component and make some changes in our &lt;code&gt;ProductsProvider&lt;/code&gt; function.&lt;br&gt;
In this function we will make it receives a prop that holds &lt;strong&gt;consumers&lt;/strong&gt; children and return the &lt;code&gt;ProductsContext.Provider&lt;/code&gt; component like so :&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;ProductsContext.Provider value={products}&amp;gt;&lt;br&gt;
     {prop.children}&lt;br&gt;
  &amp;lt;/ProductsContext.Provider&amp;gt;&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The Provider component receives a prop called value, which can be accessed from all the components that are wrapped inside Provider, and it will be responsible to grant access to the context data.&lt;br&gt;
The component will be like this after this changes :&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%2Fthnipndyl4us6gkuthmc.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%2Fthnipndyl4us6gkuthmc.png" alt="add context.provider component"&gt;&lt;/a&gt;&lt;br&gt;
**&lt;code&gt;{prop.children}&lt;/code&gt; represents the components wrapped inside the &lt;code&gt;ProductsProvider&lt;/code&gt; component in &lt;code&gt;App.js&lt;/code&gt;.&lt;br&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So, how we can use our context now ?&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;Third step :&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  useContext#&lt;br&gt;
&lt;/h1&gt;

&lt;p&gt;React has a built-in hooks such as &lt;code&gt;useState&lt;/code&gt;, &lt;code&gt;useCallback&lt;/code&gt;, &lt;code&gt;useEffect&lt;/code&gt;, etc. But the one that we’re going to talk and learn more about here is the &lt;code&gt;useContext&lt;/code&gt; hook.&lt;br&gt;&lt;br&gt;
The &lt;code&gt;useContext&lt;/code&gt; hook allows us to connect and &lt;strong&gt;consume&lt;/strong&gt; a context. The &lt;code&gt;useContext&lt;/code&gt; hook receives a single argument, which is the context that you want to have access to.&lt;br&gt;&lt;br&gt;
So, first we must import our context which is already defined from previous steps in the component we want to &lt;strong&gt;consume&lt;/strong&gt; this context :&lt;br&gt;
&lt;code&gt;import {ProductsContext} from './ProductsContext';&lt;/code&gt;&lt;br&gt;
and then we must import &lt;code&gt;useContext&lt;/code&gt; from react :&lt;br&gt;
&lt;code&gt;import {useContext} from 'react';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I will use the context in &lt;code&gt;ProductList.js&lt;/code&gt; first&lt;/em&gt;&lt;br&gt;
So, I will say &lt;br&gt;
&lt;code&gt;const products = useContext(ProductsContext);&lt;/code&gt; like so :&lt;br&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%2Fm4fbi25yu5l2pbs00c8h.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%2Fm4fbi25yu5l2pbs00c8h.png" alt="Using useContext"&gt;&lt;/a&gt;&lt;br&gt;
Now, if we &lt;code&gt;console.log(products)&lt;/code&gt; will get an array of objects that contains this products data and we can use it as we like and everywhere without using props !!&lt;br&gt;
&lt;strong&gt;Congratulations&lt;/strong&gt; 😍✌&lt;/p&gt;

&lt;p&gt;Now, we can use this data and display products in our app, display the number of products we have in &lt;code&gt;Nav.js&lt;/code&gt; component very fast like so.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;ProductList.js :&lt;/em&gt;&lt;br&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%2F5z1rszzwyzmezpbph5u9.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%2F5z1rszzwyzmezpbph5u9.png" alt="display products"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
&lt;em&gt;Nav.js :&lt;/em&gt;&lt;br&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%2Fowq4fwkyammo01ui5wpf.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%2Fowq4fwkyammo01ui5wpf.png" alt="display number of items"&gt;&lt;/a&gt;&lt;br&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;In this article, we learned more about the React Context API. The Context API came to solve problems that we were having in React applications. One of the most important is &lt;em&gt;prop-drilling&lt;/em&gt; issue. We created a simple example using the React Context API. Also, we were learned how to use the &lt;code&gt;useContext&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;I hope you will forgive me if there are any mistakes.&lt;br&gt;
Don't forget to support me 🙌🌹&lt;br&gt;
Best wishes ❤&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
  </channel>
</rss>
