<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kunal Sharma</title>
    <description>The latest articles on DEV Community by Kunal Sharma (@kunalsharma1999).</description>
    <link>https://dev.to/kunalsharma1999</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%2F662918%2F8046cad6-ec02-4e25-995e-f33155768b1a.png</url>
      <title>DEV Community: Kunal Sharma</title>
      <link>https://dev.to/kunalsharma1999</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kunalsharma1999"/>
    <language>en</language>
    <item>
      <title>Enhancing Dynamic Nature of React Application with Event Handling</title>
      <dc:creator>Kunal Sharma</dc:creator>
      <pubDate>Fri, 09 Jul 2021 12:41:09 +0000</pubDate>
      <link>https://dev.to/kunalsharma1999/enhancing-dynamic-nature-of-react-application-with-event-handling-351n</link>
      <guid>https://dev.to/kunalsharma1999/enhancing-dynamic-nature-of-react-application-with-event-handling-351n</guid>
      <description>&lt;p&gt;Starting with event handling requires us to &lt;strong&gt;understand what events mean&lt;/strong&gt;. So, to explain it I would take an example in which I am going to punch a guy which is an action. The guy who got the punch hit is basically JavaScript and now he can have a response to it which can be either to hit me back or run due to my fear. Therefore, the action to which JavaScript can respond is called an event and the response is controlled by the event handler.&lt;/p&gt;

&lt;p&gt;Now, talking of general events in an application will be:&lt;br&gt;
1)  Clicking an element&lt;br&gt;
2)  Submitting a form&lt;br&gt;
3)  Scrolling page&lt;br&gt;
4)  Hovering an element&lt;/p&gt;

&lt;p&gt;Contrasting between event handling in html and react:&lt;/p&gt;
&lt;h4&gt;
  
  
  In HTML:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onclick=”incrementCounter()”&amp;gt;Increment Counter&amp;lt;/button&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  In React:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Used in a function component
&amp;lt;button onClick={incrementCounter}&amp;gt;Increment Counter&amp;lt;/button&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;//Used in a class component
&amp;lt;button onClick={this.incrementCounter}&amp;gt;Increment Counter&amp;lt;/button&amp;gt;  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;So, it can be seen that react events are camelCase. With JSX you only pass the function instead of calling it. Use this keyword in a class component.&lt;/p&gt;

&lt;p&gt;Let’s go through one more contrast.&lt;/p&gt;
&lt;h4&gt;
  
  
  In HTML:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;a href=”#” onclick=”console.log(‘Clicked’); return false”&amp;gt;Click&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  In React:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function handleClick(e){
    e.preventDefault();
}
&amp;lt;a href=”#” onClick={handleClick}&amp;gt;Click&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;So, basically you have to call prevent default explicitly in react rather than just returning false.&lt;/p&gt;

&lt;p&gt;Another important point is that when you put the callback function to be called on the trigger of the event in order to use ‘this’ work on the callback function either you can have an arrow function or you can use binding this to the function in the constructor.&lt;/p&gt;

&lt;p&gt;1) &lt;strong&gt;Using arrow function to make ‘this’ work in callback&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;import React, { Component } from 'react'**

class About extends Component{
    constructor(props){
        super(props);
        this.state = {
            name: "Kunal Sharma"
        }
    }

    handleClick = () =&amp;gt; {
        console.log("Button has been clicked", this);
    }

    render(){
        return (
            &amp;lt;div&amp;gt;
                &amp;lt;button onClick={this.handleClick}&amp;gt;Click Me&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        )
    }
}

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

&lt;/div&gt;



&lt;p&gt;2) &lt;strong&gt;Using binding to use ‘this’ work in callback&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;import React, { Component } from 'react'

class Student extends Component{
    constructor(props){
        super(props);
        this.state = {
            name: "Kunal Sharma"
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        console.log("Button has been clicked", this);
    }

    render(){
        return (
            &amp;lt;div&amp;gt;
                &amp;lt;button onClick={this.handleClick}&amp;gt;Click Me&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        )
    }
}

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Passing Arguments to event handlers:
&lt;/h3&gt;

&lt;p&gt;1) &lt;strong&gt;Arrow Function:&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;&amp;lt;button onClick={(e)=&amp;gt;this.handleClick(id,e)}&amp;gt;Delete&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here e is react’s event object and id can be a state or props.&lt;/p&gt;

&lt;p&gt;2) &lt;strong&gt;Bind Method:&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;&amp;lt;button onClick={this.handleClick.bind(this,id)}&amp;gt;Delete&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In both the cases e is passed as an argument to the event handler.&lt;br&gt;
In the arrow function we have implemented it explicitly but with bind it is automatically done. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;There are various methods to trigger an event just like onClick. &lt;a href="https://reactjs.org/docs/events.html"&gt;https://reactjs.org/docs/events.html&lt;/a&gt; follow this link to have a glance at them and use them as per requirement following the above mentioned ways.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In order to give you much clarity on how I created an app called “Fastest Clicker First” which uses the onClick events and in the event handlers I performed operations like counting the number of times button is being clicked in 10 seconds span of time, changing the states using Boolean variables to mount/unmount and playing the game again by initializing the state to the defaults , resetting the click me button and countdown timer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;App Component:&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;import React, { Component } from "react";
import Counter from "./components/Counter";
import "./App.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      mount: false,
    };

    this.mountCounter = () =&amp;gt; this.setState({ mount: true });
    this.unmountCounter = () =&amp;gt; this.setState({ mount: false });
  }

  render() {
    return (
      &amp;lt;div className="app"&amp;gt;
        &amp;lt;h1&amp;gt;Fastest Clicker First&amp;lt;/h1&amp;gt;
        &amp;lt;div className="buttons"&amp;gt;
          {!this.state.mount ? (
            &amp;lt;button className="button" onClick={this.mountCounter}&amp;gt;
              Play Now
            &amp;lt;/button&amp;gt;
          ) : null}
          {this.state.mount ? (
            &amp;lt;button className="button" onClick={this.unmountCounter}&amp;gt;
              End Game
            &amp;lt;/button&amp;gt;
          ) : null}
        &amp;lt;/div&amp;gt;
        {this.state.mount ? &amp;lt;Counter /&amp;gt; : null}
      &amp;lt;/div&amp;gt;
    );
  }
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Counter Component:&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;import React, { Component } from "react";
import "./Counter.css";

class Counter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0,
      timeLeft: 10,
      isActiveButton: true,
      isPlayAgainButtonActive: false,
    };
  }

  incrementCount = () =&amp;gt; {
    this.setState({ count: this.state.count + 1 });
  };

  disableClickButton = () =&amp;gt; {
    this.setState({ isActiveButton: false });
  };

  componentDidMount = () =&amp;gt; {
    this.setCountdownTimer();
    this.resetClickButton();
  };

  setCountdownTimer = () =&amp;gt; {
    var timer = setInterval(() =&amp;gt; {
      if (this.state.timeLeft &amp;gt; 0) {
        this.setState({ timeLeft: this.state.timeLeft - 1 });
      } else {
        this.setState({ isPlayAgainButtonActive: true });
        clearInterval(timer);
      }
    }, 1000);
  };

  resetClickButton = () =&amp;gt; {
    setTimeout(this.disableClickButton, 10000);
  };

  refreshCounter = () =&amp;gt; {
    this.setState({ count: 0 });
    this.setState({ timeLeft: 10 });
    this.setState({ isActiveButton: true });
    this.setCountdownTimer();
    this.resetClickButton();
  };

  render() {
    return (
      &amp;lt;div className="counter"&amp;gt;
        &amp;lt;h2&amp;gt;Time left is {this.state.timeLeft}&amp;lt;/h2&amp;gt;
        &amp;lt;h2&amp;gt;Total number of clicks are {this.state.count}&amp;lt;/h2&amp;gt;
        &amp;lt;div className="btns"&amp;gt;
          &amp;lt;button
            className="btn"
            onClick={this.incrementCount}
            disabled={!this.state.isActiveButton}
          &amp;gt;
            Click Me
          &amp;lt;/button&amp;gt;
          {this.state.isPlayAgainButtonActive ? (
            &amp;lt;button className="button" onClick={this.refreshCounter}&amp;gt;
              Play Again
            &amp;lt;/button&amp;gt;
          ) : null}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

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

&lt;/div&gt;



&lt;p&gt;Here, in the code you can see in the buttons I have used onClick and in the JSX I have added a callback function which basically will perform the desired response.&lt;/p&gt;

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

&lt;p&gt;&lt;em&gt;You can play this game on &lt;a href="https://fastest-clicker-first-2pnc89cjb-kunalsharma1999.vercel.app/"&gt;https://fastest-clicker-first-2pnc89cjb-kunalsharma1999.vercel.app/&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Hope, this example creates a better level of understanding regarding triggering an event and then handling the responses.&lt;/p&gt;

&lt;p&gt;That’s it for the post.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Having a good grip over the react code flow using Lifecycle Hooks/Methods</title>
      <dc:creator>Kunal Sharma</dc:creator>
      <pubDate>Thu, 08 Jul 2021 09:05:50 +0000</pubDate>
      <link>https://dev.to/kunalsharma1999/having-a-good-grip-over-the-react-code-flow-using-lifecycle-hooks-methods-32ic</link>
      <guid>https://dev.to/kunalsharma1999/having-a-good-grip-over-the-react-code-flow-using-lifecycle-hooks-methods-32ic</guid>
      <description>&lt;p&gt;React lets us define components as classes or as functions.&lt;br&gt;
We know that component class can be defined by extending React.Component and the only required method in that sub class is render().&lt;/p&gt;

&lt;p&gt;But components also have various lifecycle methods that you can override to run your code at a particular time in the process. These methods are categorized into four groups as follows:&lt;br&gt;
1) Mounting&lt;br&gt;
2) Updating&lt;br&gt;
3) Error Boundaries&lt;br&gt;
4) Unmounting&lt;/p&gt;

&lt;p&gt;In order to understand these methods better we’ll implement a counter component and utilize all the lifecycle methods.&lt;br&gt;
Initially, the counter component is having a constructor method which after being called will be followed by the render method.&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, { Component } from 'react'

class Counter extends Component {
    constructor(props){
        console.log('constructors');
        super(props)

        this.state = {
            counter: 0
        }

        this.increment = () =&amp;gt;{
            this.setState({counter: this.state.counter+1});
        }

        this.decrement = () =&amp;gt;{
            this.setState({counter: this.state.counter-1});
        }
    }

    render() {
    console.log('render');
        return (
            &amp;lt;div&amp;gt;
                &amp;lt;button onClick={this.increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
                &amp;lt;button onClick={this.decrement}&amp;gt;Decrement&amp;lt;/button&amp;gt;
                &amp;lt;div className="counter"&amp;gt;
                Counter:{this.state.counter}
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        )
    }
}

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

&lt;/div&gt;



&lt;p&gt;As long as you’ll be clicking the increment or decrement button, the same number of times render method will be called.&lt;br&gt;
Now lets introduce a few life cycle methods.&lt;br&gt;
First one is &lt;strong&gt;componentDidMount&lt;/strong&gt; method and it is called right after the render method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidMount(){    
        console.log("Components Did Mount");
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; This method is called after the render method but only when the component is constructed.&lt;/p&gt;

&lt;p&gt;However, there is another method &lt;strong&gt;componentDidUpdate&lt;/strong&gt; which takes few parameters i.e. previous props, previous state and snapshot.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidUpdate(preProps, prevState, snapshot){    
        console.log("Components Did Update");
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On constructing the component, componentDidUpdate will not be called. Once you click increment or a decrement button this method will be called after the render method as many times you click. &lt;/p&gt;

&lt;p&gt;Now, lets add the ability to mount and unmount this counter. We need to do that in App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;constructor(props){
        super(props)

        this.state = {
            mount: true
        }

        this.mountCounter = () =&amp;gt; this.setState({mount: true});
        this.unmountCounter = () =&amp;gt; this.setState({mount: false});
    }

    render() {
        return (
            &amp;lt;div&amp;gt;
            &amp;lt;button onClick={this.mountCounter} disabled={this.state.mount}&amp;gt;Mount Counter&amp;lt;/button&amp;gt;
            &amp;lt;button onClick={this.unmountCounter} disabled={this.state.mount}&amp;gt;Unmount Counter&amp;lt;/button&amp;gt;
            {this.state.mount ? &amp;lt;Counter/&amp;gt; : null}
            &amp;lt;/div&amp;gt;
        )
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s add another life cycle method &lt;strong&gt;componentWillUnmount&lt;/strong&gt;. Add this method in the counter component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; componentWillUnmount(){    
        console.log("Components Will Unmount");
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As soon as the component is kicked out this method will be called and you can achieve this by clicking the unmount counter button. &lt;br&gt;
But when you click mount counter button the constructor is triggered again along with the render and componentDidMount method respectively.&lt;/p&gt;

&lt;p&gt;These are the most frequently used life cycle methods. &lt;/p&gt;
&lt;h3&gt;
  
  
  Other methods are:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;shouldComponentUpdate&lt;/strong&gt; with two parameters next props and next state and generally returns true by default.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;shouldComponentUpdate(nextProps, nextState){
        return true;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method helps react know if render should be triggered or not. Use case for it might be that your state or props are updated and you don’t need render to be triggered because you are not changing anything in the UI and your method is too expensive to be computed.&lt;/p&gt;

&lt;p&gt;Modify the following in the App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.state = {
            mount: true,
            ignoreProp: 0
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add a method in the constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.ignoreProp = () =&amp;gt; this.setState({ignoreProp: Math.random()});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pass this prop in the counter component and add a button to trigger.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={this.ignoreProp}&amp;gt;Ignore Prop&amp;lt;/button&amp;gt;
            {this.state.mount ? &amp;lt;Counter ignoreProp={this.state.ignoreProp}/&amp;gt; : null}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we click on ignore prop button its going to call render and component did update method because something changed on the parent and is passed down to 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;    shouldComponentUpdate(nextProps, nextState){
        if(nextProps.ignoreProp &amp;amp;&amp;amp; this.props.ignoreProp !== nextProps.ignoreProp)
        {
            console.log('Should Component Update - DO NOT RENDER')
            return false;
        }
        console.log('Should Component Update - RENDER')
        return true;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, adding this if statement to check whether the current ignore prop value is different from the next prop value and returning false thereby not allowing react to call render method because there is no change in the UI.&lt;/p&gt;

&lt;p&gt;The next method is a static method and is called before every other method. &lt;strong&gt;getDerivedStateFromProps&lt;/strong&gt; with two parameters props and state. The purpose of this method is to give you a chance to copy any values from props that you may be interested in transferring over to state.&lt;/p&gt;

&lt;p&gt;To illustrate, add a random value in the state of App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; this.state = {
            mount: true,
            ignoreProp: 0,
            seed: 40
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add a method seed generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.seedGenerator = () =&amp;gt; this.setState({seed: Number.parseInt(Math.random*100)});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pass the seed as a prop to the counter component and also a button to trigger.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={this.seed}&amp;gt;Seed Generator&amp;lt;/button&amp;gt;
            {this.state.mount ? &amp;lt;Counter ignoreProp={this.state.ignoreProp} seed={this.state.seed}/&amp;gt; : null}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Anything you assign to this getDerivedStateFromProps gets assigned to state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    static getDerivedStateFromProps(props, state){
        return null;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, if you don’t want to change state you simply return null.&lt;br&gt;
Also, in the counter component’s state add seed value as 0 for default.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  this.state = {
            counter: 0,
            seed: 0
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, to check its functioning we add a if statement to check if seed exists on the props and the seed that is in our state is not equal to that seed that’s passed then we’ll return seed value that’s props.seed and set the counter to props.seed as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    static getDerivedStateFromProps(props, state){
        if(props.seed &amp;amp;&amp;amp; state.seed !== props.seed){
            return {
                seed: props.seed,
                counter: props.seed
            }
        }
        return null;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the counter will start at 40 as seed value in App.js is initialized as 40. Clicking Seed Generator button will change the value of the counter.&lt;/p&gt;

&lt;p&gt;So, basically it copies props into state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Since it is a static method, we don’t have access to instance of the object.&lt;/p&gt;

&lt;p&gt;Next method is &lt;strong&gt;getSnapShotBeforeUpdate&lt;/strong&gt; which is called just before render and takes previous props and previous state as arguments and returns a value. This method allows us to capture some properties that are not stored in the state before we re-render that component. Whatever is returned here is passed to componentDidUpdate as a third parameter called snapshot.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; getSnapshotBeforeUpdate(prevProps, prevState)
    {
        console.log('Get Snapshot Before Update');
        return null;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, there is a method called &lt;strong&gt;componentDidCatch&lt;/strong&gt; which is part of the error boundaries and takes two parameters error and info and gives a chance to gracefully handle errors that we run into.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    componentDidCatch(error, info){
        console.log('Component Did Catch');

        this.setState({error, info});
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, lets create a component which produces a error to check its functionality.&lt;br&gt;
We’ll create a ErrorComponent and return a div with some non-existent value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const ErrorComponent = () =&amp;gt; &amp;lt;div&amp;gt;{props.ignore}&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Put that component to be rendered in the counter components render method.&lt;br&gt;
When you’ll run this application, you’ll get an error and component did catch will be called. If you don’t use this method, you’ll lose everything which is rendered in the browser.&lt;br&gt;
In the render method you can check for the error and get it displayed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  render() {
        console.log('render');

        if(this.state.error)
        {
            return &amp;lt;div&amp;gt;We have encountered an error! {this.state.error.message}&amp;lt;/div&amp;gt;
        }

        return (
            &amp;lt;div&amp;gt;
            &amp;lt;button onClick={this.increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
            &amp;lt;button onClick={this.decrement}&amp;gt;Decrement&amp;lt;/button&amp;gt;
            &amp;lt;div className="counter"&amp;gt;
                Counter:{this.state.counter}
            &amp;lt;/div&amp;gt;
            &amp;lt;ErrorComponent/&amp;gt;
            &amp;lt;/div&amp;gt;
        )
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, comes a doubt that we can use these lifecycle hooks in a class component but how can we use it in a functional component. For that we can use &lt;strong&gt;useEffect&lt;/strong&gt; hook which came in React 16.8. It will help us to detect the state changes and props changes also. It will perform all the functionalities of componentDidMount, componentWillUnmount and componentDidUpdate.&lt;/p&gt;

&lt;p&gt;First of all you’ll have to import useEffect and useState from react.&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, { useEffect, useState } from 'react'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use the useState method for the counter functionality in 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; const [count, setCount]=useState(0);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add a button to increase the count using setCount function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;button onClick={() =&amp;gt; {setCount(count+1)}}&amp;gt;Click to increment count {count}&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order to detect the state changes we use the useEffect method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   useEffect(()=&amp;gt;{
        console.log(count);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, as soon as the state will change this useEffect method will be triggered and you can perform any operation as per your wish. &lt;br&gt;
But if you want it to be triggered at a specific change of state you can do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(()=&amp;gt;{
        console.log(count);
    },[count===3])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will trigger only when count is 3.&lt;br&gt;
Similarly, you can also pass the count as a prop from the parent to the child component and use the useEffect method in the child class to detect the changes and perform some operation.  &lt;/p&gt;

&lt;p&gt;If you want to use this useEffect hook in such a way that you don’t want to execute componentDidMount and componentDidUpdate at the same time the following is the procedure to do so.&lt;br&gt;
Initialize a reference hook which returns mutable object whose current property is initialized with false.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const didMountRef = useRef(false)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, modify the useEffect method as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    if (didMountRef.current) {
      doStuff()
    } else didMountRef.current = true
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Implementing this will ensure that initially didMountRef.current is false and for the first call it acts as componentDidMount but after the mounting didMountRef.current will become true and for the next times it will work as componentDidUpdate.&lt;br&gt;
Also, you can perform a clean up in the useEffect hook which basically ensures that after each update previous events listened or subscriptions are deleted to maintain better performance and avoid app from crashing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  useEffect(() =&amp;gt; {
      effect
      return () =&amp;gt; {
          cleanup
      }
  }, [input])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion:
&lt;/h3&gt;

&lt;p&gt;useEffect() runs after every render. So, it’s like componentDidMount(), componentDidUpdate() and componentWillUnmount() all at the same time. So, still you can find use cases for class components because of access to specific lifecycle methods though react hooks introduced in React 16.8 resolve many issues like managing of state and optimization.&lt;/p&gt;

&lt;p&gt;That's it for the post.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding State in React</title>
      <dc:creator>Kunal Sharma</dc:creator>
      <pubDate>Wed, 07 Jul 2021 09:38:29 +0000</pubDate>
      <link>https://dev.to/kunalsharma1999/understanding-state-in-react-3p29</link>
      <guid>https://dev.to/kunalsharma1999/understanding-state-in-react-3p29</guid>
      <description>&lt;p&gt;When we start building a react application, we break our application into multiple components. So, there is an App Component which is the main component and we then add the remaining components inside to build our application.&lt;/p&gt;

&lt;p&gt;So, before we go to state let us learn about &lt;strong&gt;props&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Props is basically a way to pass data between components.&lt;/p&gt;

&lt;p&gt;Suppose, we define a const name in App Component like as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const name = “Kunal Sharma”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now how to pass this data to the child components?&lt;br&gt;
The answer to this is, we can do it by using props.&lt;/p&gt;

&lt;p&gt;For eg. if I want that name in my header component I can just write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Header name={name}&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if I am using function based header component what I can do is just write props in the parenthesis.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Header = (props) =&amp;gt; (
return &amp;lt;h3&amp;gt;{props.name}&amp;lt;/h3&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By this way I can pass as much information as I want.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: We can only pass props in one direction i.e. from parent to child.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now let’s come to &lt;strong&gt;state&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;State is a JavaScript object that contains a piece of data. You can imagine it as a variable in react app. The difference is though that this state or variable reacts to changes. So, if something happens in our app. If that piece of variable or state gets updated, the component is automatically going to re-render and your component is going to react to that change.&lt;/p&gt;

&lt;p&gt;For eg. If we take a counter variable initialized as 0. Also, we have an increment function to add 1 to the counter variable. Now, lets create a button to increment the counter and what we see in the view is variables in react don’t react to changes. But if we console log the steps you are going to see the value of counter is getting incremented.&lt;/p&gt;

&lt;p&gt;However, if we use state react automatically is going to know what parts of the UI to re-render and this makes react super powerful and fast.&lt;/p&gt;

&lt;p&gt;Now when we talk about state usage in &lt;em&gt;previous versions&lt;/em&gt; of react, we could create a state only in a class component. So, state was private and fully controlled by the component. The most important benefit of state became its ability to be modified or get updated.&lt;/p&gt;

&lt;p&gt;There are two ways to initialize the state in a react component:&lt;br&gt;

  1) Directly inside class (without constructor)
  &lt;br&gt;
Directly inside class:&lt;br&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Class Student extends Component{
//States – Here it is a class property
state = {
name : “Kunal Sharma”,
rollNo: this.props.rollNo
}
render(){
return(
&amp;lt;h1&amp;gt;Hello {this.state.name} your roll number is {this.state.rollNo}&amp;lt;/h1&amp;gt;
)
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;




&lt;br&gt;

  2) Inside the constructor (with constructor)
  &lt;br&gt;
Inside the constructor:&lt;br&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Class Student extends Component{
constructor(props){
//It is required to call the parent class constructor
super(props);
//States
this.state = {
name : “Kunal Sharma”,
rollNo: this.props.rollNo
}
}
render(){
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;When the component class is created, we know that the constructor is the first method called, so it’s the right place to add state and also class instance has already been created in memory, so you can use this to set properties on it.&lt;br&gt;
&lt;strong&gt;Note: When we write a constructor, make sure to call the parents class’ constructor by super(props) as when you call super with props React will make props available across the component through this.props.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;br&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Updating a State
&lt;/h3&gt;

&lt;p&gt;setState() Method is used to update states.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.state = {
name : “Kunal Sharma”
}
this.setState({
name: “Kunal”
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Second form of setState() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.setState(function(state,props){
return{
};
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It accepts a function rather than an object.&lt;br&gt;
It receives the previous state as the first argument and props at the time the update is applied as the second argument.&lt;/p&gt;

&lt;p&gt;But now after the release of React Hooks in React 16.8 we can also use the capabilities of the state in a function based component as well.&lt;/p&gt;

&lt;p&gt;So, to use state in function based components we import useState from the react library.&lt;br&gt;
Suppose, continuing the counter example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [counter, setCounter] = useState(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-Here, 0 is the basically the initial data we want to use.&lt;br&gt;
-counter is the actual piece of state.&lt;br&gt;
-setCounter is the function that allows us to change the counter.&lt;/p&gt;

&lt;p&gt;So, make sure that you don’t increment the counter as counter += 1 and use setCounter instead.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setCounter((prev) =&amp;gt; prev + 1);
//or setCounter(counter + 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, it actually works.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: We can only pass state in one direction i.e. from parent to child and state is dependent on one component.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;State in a react application is a object that contains information that may change in its lifetime and gets reflected in the view automatically.&lt;/p&gt;

&lt;p&gt;That's it for this post.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
