<?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: punya2004</title>
    <description>The latest articles on Forem by punya2004 (@punya2004).</description>
    <link>https://forem.com/punya2004</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%2F632227%2Fa9fcdba3-b049-480a-8408-3247538d3583.jpg</url>
      <title>Forem: punya2004</title>
      <link>https://forem.com/punya2004</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/punya2004"/>
    <language>en</language>
    <item>
      <title>Migrating From Class To Functional Components With Hooks </title>
      <dc:creator>punya2004</dc:creator>
      <pubDate>Tue, 18 May 2021 12:39:36 +0000</pubDate>
      <link>https://forem.com/punya2004/migrating-from-class-to-functional-components-with-hooks-2j69</link>
      <guid>https://forem.com/punya2004/migrating-from-class-to-functional-components-with-hooks-2j69</guid>
      <description>&lt;h2&gt;
  
  
  What’s the difference,which should you use in your app,and why?
&lt;/h2&gt;

&lt;p&gt;Since React is so popular among developers today, this blog is &lt;br&gt;
intended to give you the pros and cons of React hooks vs. classes &lt;br&gt;
through React &lt;code&gt;useState()&lt;/code&gt; and &lt;code&gt;useEffect()&lt;/code&gt;’s hooks API.&lt;/p&gt;
&lt;h2&gt;
  
  
  Rendering JSX:
&lt;/h2&gt;

&lt;p&gt;First of all, the clear difference is the syntax. Just like in&lt;br&gt;
their names, a functional component is just a plain JavaScript function that returns JSX. A class component is a JavaScript class that extends &lt;code&gt;React.Component&lt;/code&gt; which has a render method. &lt;/p&gt;

&lt;p&gt;Let’s take a look into a simple example.&lt;/p&gt;
&lt;h4&gt;
  
  
  In functional components:
&lt;/h4&gt;


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

const FunctionalComponent = () =&amp;gt; 
{
    return &amp;lt;h1&amp;gt;Hello, world&amp;lt;/h1&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  In class components:
&lt;/h4&gt;


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

class ClassComponent extends Component {
 render() {
   return &amp;lt;h1&amp;gt;Hello, world&amp;lt;/h1&amp;gt;;
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Passing props:
&lt;/h2&gt;

&lt;p&gt;Inside a functional component, we are passing props as an argument of the function. Note that we are using &lt;code&gt;destructuring&lt;/code&gt; here.&lt;/p&gt;
&lt;h4&gt;
  
  
  In functional components:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Component name="punya" /&amp;gt;
&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;const FunctionalComponent = ({ name }) =&amp;gt; {
 return &amp;lt;h1&amp;gt;Hello, {name}&amp;lt;/h1&amp;gt;;
};

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

&lt;/div&gt;


&lt;p&gt;we can write it without 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 FunctionalComponent = (props) =&amp;gt; {
 return &amp;lt;h1&amp;gt;Hello, {props.name}&amp;lt;/h1&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  In class components:
&lt;/h4&gt;

&lt;p&gt;Since it is a class, you need to use this to refer to props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ClassComponent extends React.Component {
  render() {
    const { name } = this.props;
    return &amp;lt;h1&amp;gt;Hello, { name }&amp;lt;/h1&amp;gt;;
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Handling state:
&lt;/h2&gt;

&lt;p&gt;Handling state was only doable in a class component until&lt;br&gt;
recently, React Hook &lt;code&gt;useState&lt;/code&gt; was introduced to allow developers to write &lt;code&gt;stateful&lt;/code&gt; functional components.&lt;/p&gt;
&lt;h4&gt;
  
  
  Handling state in functional components:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const FunctionalComponent = () =&amp;gt; {
 const [count, setCount] = React.useState(0);

 return (
   &amp;lt;div&amp;gt;
     &amp;lt;p&amp;gt;count: {count}&amp;lt;/p&amp;gt;
     &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Click&amp;lt;/button&amp;gt;
   &amp;lt;/div&amp;gt;
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;To use state variables in a functional component, we need to use &lt;br&gt;
&lt;code&gt;useState&lt;/code&gt; Hook, which takes an argument of &lt;code&gt;initial state&lt;/code&gt; and&lt;br&gt;
returns the current state and a &lt;code&gt;function&lt;/code&gt; that updates it.&lt;/p&gt;
&lt;h4&gt;
  
  
  Handling state in class components:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class ClassComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     count: 0
   };
 }

 render() {
   return (
     &amp;lt;div&amp;gt;
       &amp;lt;p&amp;gt;count: {this.state.count} times&amp;lt;/p&amp;gt;
       &amp;lt;button onClick={() =&amp;gt; this.setState({ count: this.state.count + 1 })}&amp;gt;
         Click
       &amp;lt;/button&amp;gt;
     &amp;lt;/div&amp;gt;
   );
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The idea is still the same but a class component handles state a&lt;br&gt;
bit differently. Basically, without implementing the constructor and calling super(props), all the state variables that you are&lt;br&gt;
trying to use will be undefined. So let’s define the constructor first. &lt;br&gt;
Inside the constructor, you will make a state object with a state&lt;br&gt;
key and initial value. And inside JSX, we use &lt;code&gt;this.state.count&lt;/code&gt; to access the value of the state .&lt;/p&gt;
&lt;h2&gt;
  
  
  Lifecycle Methods:
&lt;/h2&gt;

&lt;p&gt;As you already know, lifecycles play an important role in the&lt;br&gt;
timing of rendering. &lt;/p&gt;
&lt;h4&gt;
  
  
  In class components:
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;On Mounting (componentDidMount):&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ClassComponent extends React.Component {
 componentDidMount() {
   console.log("Hello");
 }

 render() {
   return &amp;lt;h1&amp;gt;Hello, World&amp;lt;/h1&amp;gt;;
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;On Unmounting (componentWillUnmount):&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ClassComponent extends React.Component {
 componentWillUnmount() {
   console.log("Bye");
 }

 render() {
   return &amp;lt;h1&amp;gt;Bye, World&amp;lt;/h1&amp;gt;;
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  In functional components:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const FunctionalComponent = () =&amp;gt; {
 React.useEffect(() =&amp;gt; {
   console.log("Hello");//componentDidMount()
      return () =&amp;gt; {//componentWillUnmount()
     console.log("Bye");
   };
 }, []);
 return &amp;lt;h1&amp;gt;Hello, World&amp;lt;/h1&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replacing &lt;code&gt;componentDidMount&lt;/code&gt;, We use the &lt;code&gt;useEffect&lt;/code&gt; hook with the second argument of []. The second argument of the &lt;code&gt;useState&lt;/code&gt; hook is normally an array of a state(s) that changes, and &lt;code&gt;useEffect&lt;/code&gt; will be only called on these selected changes. But when it’s an empty array like this example, it will be called once on mounting. This is a perfect replacement for a &lt;code&gt;componentDidMount&lt;/code&gt;. &lt;code&gt;componentDidMount&lt;/code&gt; is a lifecycle method that is called once after the first render.&lt;/p&gt;

&lt;p&gt;unmounting inside the &lt;code&gt;useEffect&lt;/code&gt; function. This is especially&lt;br&gt;
useful when you have to clean up the subscriptions such as a &lt;br&gt;
clearInterval function, otherwise it can cause a severe memory &lt;br&gt;
leak on a bigger project. One advantage of using &lt;code&gt;useEffect&lt;/code&gt; is &lt;br&gt;
that we can write functions for both mounting and unmounting in &lt;br&gt;
the same place.&lt;/p&gt;

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

&lt;p&gt;I would like to conclude that functional components are taking&lt;br&gt;
over modern React in the foreseeable future. As we noticed in the examples, a functional component is written shorter and simpler, which makes it easier to develop, understand, and test. Class&lt;br&gt;
components can also be confusing with so many uses of this. Using functional components can easily avoid this kind of mess and keep everything clean.&lt;/p&gt;

</description>
      <category>react</category>
      <category>devops</category>
      <category>reactjsdeveloper</category>
      <category>programming</category>
    </item>
    <item>
      <title>Learn How TO Utilize  Closures In JavaScript</title>
      <dc:creator>punya2004</dc:creator>
      <pubDate>Mon, 17 May 2021 13:19:59 +0000</pubDate>
      <link>https://forem.com/punya2004/learn-how-to-utilize-closures-in-javascript-oo4</link>
      <guid>https://forem.com/punya2004/learn-how-to-utilize-closures-in-javascript-oo4</guid>
      <description>&lt;p&gt;Closures are a very powerful mechanism in the JavaScript&lt;br&gt;
programming language. In this, we will learn about closures and the benefits of using them in your JavaScript code.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is Closure?
&lt;/h2&gt;

&lt;p&gt;A closure is a function along with its lexical environment bundled together. That means the function has access to its outer&lt;br&gt;
function scope even after the outer function has returned.&lt;/p&gt;

&lt;p&gt;A closure can remember and access variables and arguments of its&lt;br&gt;
outer function even after the function has finished.&lt;/p&gt;
&lt;h2&gt;
  
  
  Let's see what is a Lexical Scope?
&lt;/h2&gt;

&lt;p&gt;A lexical scope or static scope in JavaScript refers to the accessibility of the variables, functions, and objects based on their physical location in the source code.&lt;/p&gt;
&lt;h4&gt;
  
  
  For example:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   function display() {
        var name = 'punya'; 
        function displayName() { 
            console.log(name); 
        }
        displayName();
    }
    display();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Output:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7306cZen--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fr7swposa3nq776st64.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7306cZen--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fr7swposa3nq776st64.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;display()&lt;/code&gt; creates a local variable called name and a function called &lt;code&gt;displayName()&lt;/code&gt;. The &lt;code&gt;displayName()&lt;/code&gt; function is an inner function that is defined inside &lt;code&gt;display()&lt;/code&gt; and is available only within the body of the &lt;code&gt;display()&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Note that the &lt;code&gt;displayName()&lt;/code&gt; function has no local variables of its own. However, since inner functions have access to the variables of outer functions, &lt;code&gt;displayName()&lt;/code&gt; can access the variable name declared in the parent function, &lt;code&gt;display()&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Let’s look at some practical examples of closures :
&lt;/h2&gt;
&lt;h4&gt;
  
  
  Example 1:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Counter() {
            var counter = 0;

            function IncreaseCounter() {
                return counter += 1;
            };

            return IncreaseCounter;
        }

        var counter = Counter();
        console.log("Value of Counter is:",counter()); 
        console.log("Value of Counter is:",counter());
        console.log("Value of Counter is:",counter()); 
        console.log("Value of Counter is:",counter());

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

&lt;/div&gt;

&lt;h4&gt;
  
  
  Output:
&lt;/h4&gt;

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

&lt;p&gt;In the above example, outer function Counter returns the reference of inner function &lt;code&gt;IncreaseCounter()&lt;/code&gt;. &lt;code&gt;IncreaseCounter&lt;/code&gt; increases the outer variable counter to one. So calling inner function multiple time will increase the counter to one each time. So the behaviour of closure is that the inner function is returned from the outer function before being&lt;br&gt;
executed. &lt;/p&gt;

&lt;p&gt;####Example 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   function Counter() {

        var counter = 0;

        setTimeout(function () {
            var innerCounter = 0;
            counter += 1;
            console.log("counter value is = " + counter);

            setTimeout(function () {
                counter += 1;
                innerCounter += 1;
                console.log("counter value is = " + counter + ", innerCounter value is = " + innerCounter)
            }, 500);

        }, 1000);
    };

    Counter();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output:
&lt;/h4&gt;

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

&lt;p&gt;As per the closure definition, when counter() called it will first execute the 1st &lt;code&gt;setTimeout()&lt;/code&gt; after 500ms and 2nd&lt;br&gt;
&lt;code&gt;setTimeout()&lt;/code&gt; is called after 1000ms.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advantages of using closures:
&lt;/h2&gt;

&lt;p&gt;It can useful for Data Encapsulation which means it is useful in&lt;br&gt;
hiding implementation detail in JavaScript.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example :
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var counter = (function () {
        var privateCounter = 0;
        function changeBy(val) {
            privateCounter += val;
        }
        return {
            increment: function () {
                changeBy(1);
            },
            decrement: function () {
                changeBy(-1);
            },
            value: function () {
                return privateCounter;
            }
        };
    })();

    console.log("Counter value is: ",counter.value()); 
    counter.increment();
    counter.increment();
    console.log("Counter value is: ",counter.value()); 
    counter.decrement();
    console.log("Counter value is: ",counter.value()); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output:
&lt;/h4&gt;

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

&lt;h2&gt;
  
  
  Disadvantages of closures:
&lt;/h2&gt;

&lt;p&gt;1: Till the time its active, the memory can’t be garbage collected.&lt;/p&gt;

&lt;p&gt;2: It slows down the performance, because function within other &lt;br&gt;
function creates duplicate in memory.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>codereview</category>
    </item>
    <item>
      <title>Getting Started With React Context API - A Deep Dive</title>
      <dc:creator>punya2004</dc:creator>
      <pubDate>Sun, 16 May 2021 14:37:20 +0000</pubDate>
      <link>https://forem.com/punya2004/getting-started-with-react-context-api-a-deep-dive-562d</link>
      <guid>https://forem.com/punya2004/getting-started-with-react-context-api-a-deep-dive-562d</guid>
      <description>&lt;p&gt;So it’s my first blog and had a thought about posting something that could be helpful for React-developers beginners like ME. So I’ve been working in react for last 3–4 months and one rookie problem that most of us face while building your own first big project.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Context API?
&lt;/h2&gt;

&lt;p&gt;Context API is a way to enable components to share some data without explicitly passing via each component manually. Context is like a global object to the React component sub-tree.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why we need Context API ?
&lt;/h2&gt;

&lt;p&gt;Nearly every developer knows that React components are structured like a tree. There is one root node where all the components are connected. In this tree structure, the data flows in only one direction — from top to bottom.&lt;/p&gt;

&lt;p&gt;The problem of prop drilling arises when you create a tree structure of several components and the state created in higher level component you try to use it in lower level components. In such case you need to pass that as prop through all component levels, which is not a good practice.&lt;/p&gt;

&lt;p&gt;One line definition would be “API which is created in React itself and provides a way to pass props down the whole tree component at every level.”&lt;/p&gt;

&lt;h2&gt;
  
  
  There are different methods to use context in you React-app, Here is how I use it :
&lt;/h2&gt;

&lt;p&gt;1.First I created A StateProvider.js file which integrated my app to context API&lt;/p&gt;

&lt;h4&gt;
  
  
  StateProvider.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { createContext, useContext, useReducer } from "react";

export const stateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) =&amp;gt; (

    &amp;lt;stateContext.Provider value={useReducer( reducer, initialState )}&amp;gt;
        {children}
    &amp;lt;/stateContext.Provider&amp;gt;
)

export const useStateValue = () =&amp;gt; useContext(stateContext);

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

&lt;/div&gt;



&lt;p&gt;2.Then I used The StateProvider in index.js allowing context to be used in App component.&lt;/p&gt;

&lt;h4&gt;
  
  
  Index.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Reducer, { initialState } from './Reducer';
import { StateProvider } from './StateProvider';

ReactDOM.render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;StateProvider initialState={initialState} reducer={Reducer}&amp;gt;
    &amp;lt;App /&amp;gt;
    &amp;lt;/StateProvider&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;,
  document.getElementById('root')
);

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

&lt;/div&gt;



&lt;p&gt;Now in StateProvider.js I created context using createContext() method in react, And using it in useContext method you can can read the current value of states through the components. Then you create StateProvider function where you pass parameters like reducer , initialState and children props which will be root(App.js) component (because we need to use the state through out all the tree).&lt;/p&gt;

&lt;p&gt;So now in  index.js I wrapped the  component with provider I just created as StateProvider passing it intialstate and reducer from reducer.js as created in the code below.&lt;/p&gt;

&lt;p&gt;3.Then I created reducer.js file where I defined intialState and reducer function.&lt;/p&gt;

&lt;h4&gt;
  
  
  reducer.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const initialState = {
    user: null,
}

function Reducer (state, action) {
    console.log(action)
    switch(action.type) {

        case 'SET_USER':
            return {
                ...state,
                user: action.user
            }
         default:
            return state;
        }
}

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

&lt;/div&gt;



&lt;p&gt;4.Then using useStateValue() i.e. useContext() I was able use my state anywhere I want,&lt;/p&gt;

&lt;h4&gt;
  
  
  App.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from 'react';
import Login from './Login';
import { auth } from './firebase/config';
import { useStateValue } from './StateProvider';

function App() {

  const [{ user }, dispatch] = useStateValue();

  useEffect(() =&amp;gt; {
    const unsubscribe = auth.onAuthStateChanged((authuser) =&amp;gt; {
      if(authuser){

        dispatch({
         type: 'SET_USER',
          user: authuser
        })
      } else{    
        dispatch({
          type: 'SET_USER',
          user: null
        })
      }
    })
    return () =&amp;gt; {
      unsubscribe();
    }
  }, [])

  console.log("user is...", user)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the initialState is an object initializing all the variables that you want to use in tree and reducer function will take care of updating the DOM of that state.&lt;/p&gt;

&lt;p&gt;Now in App.js using useStateValue variable created in StateProvider.js I accessed the current value of user. useStateValue i.e. useContext returns an array where first value is state i.e. user written as {state} and second is dispatch method which will dispatch the new value of state and type of action. Since it need to be performed only one time when page renders I use dispatch method in useEffect hook.&lt;/p&gt;

&lt;p&gt;Here I set type as “SET_USER” and value of user as authuser that I got from firebase . So now it passes type as action.type and user as action.User which is updated in “SET_USER” case of switch in reducer function. I updated the user state using rest operator returning previous value and updating only user.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>coadingdays</category>
    </item>
  </channel>
</rss>
