<?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: Vutukuri Sathvik</title>
    <description>The latest articles on DEV Community by Vutukuri Sathvik (@pa1sathvik).</description>
    <link>https://dev.to/pa1sathvik</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%2F671389%2Fc1e36ba9-8261-410d-b75e-cb77f2666e8b.png</url>
      <title>DEV Community: Vutukuri Sathvik</title>
      <link>https://dev.to/pa1sathvik</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pa1sathvik"/>
    <language>en</language>
    <item>
      <title>React useState hook usage</title>
      <dc:creator>Vutukuri Sathvik</dc:creator>
      <pubDate>Wed, 21 Jul 2021 15:25:24 +0000</pubDate>
      <link>https://dev.to/pa1sathvik/react-usestate-hook-usage-b8</link>
      <guid>https://dev.to/pa1sathvik/react-usestate-hook-usage-b8</guid>
      <description>&lt;p&gt;Hi everyone, today we will see how to use React useState hook.&lt;/p&gt;

&lt;p&gt;Hooks are a new addition in React 16.8. They let u use state and other React features without writing a class.&lt;/p&gt;

&lt;p&gt;Before React 16.8 we don't have state feature usage in functional components as if they were like side characters in React.&lt;/p&gt;

&lt;p&gt;From React 16.8 , React team decided to make functional components as main roles in react development with introduction of hooks. Hooks plays a pivotal role in bridging the gap between State and functional components. Now we can develop React applications with major usage of functional components(I am doing the same now, Though I don't dare to rewrite existing class based components).&lt;/p&gt;

&lt;p&gt;Ok, let get into React.useState('Trust me I will not bore you with classic, traditional &lt;code&gt;You clicked {count} times&lt;/code&gt; example').&lt;/p&gt;

&lt;p&gt;In class based components we use this.state() to declare state variables and its initial values. A good fat example below in which state maintains multiple data.&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 = {
            currentPageBuilds: [],
            downloadedData: [],
            filteredData: [],
            builds: [],
            _sort: 'submittedDate',
            _page: 1,
            _order: 'desc',
            _limit: 10,
            _Type: 0,
            _boxId: '',
            boxName: '',
            selectedRows: { data: [] },
            q: '',
            totalCount: 0,
            loading: false,
            isFiltered: false,
            failure: false,
        };

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

&lt;/div&gt;



&lt;p&gt;Now we will see how to use useState() in Functional Components.&lt;br&gt;
First we will import the required modules 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,{useState} from 'react'
/*here we have imported the useState to maintain the state of the React component.
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we will create test functional component to use state.&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,{useState} from 'react'

function State() {

    return (
        &amp;lt;div&amp;gt;

        &amp;lt;/div&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;Now we will create state variable using React.useState() to store data returned by Free JSON API &lt;a href="https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8" rel="noopener noreferrer"&gt;Link&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;In the above declaration of state  We used array destructuring to give names to our current state and function to update that state, &lt;strong&gt;characters&lt;/strong&gt; holds characters data returned by API, &lt;strong&gt;setCharactersData&lt;/strong&gt; function is used to set/update data to &lt;strong&gt;characters&lt;/strong&gt; variable. As part of &lt;strong&gt;useState([])&lt;/strong&gt; you are using react hook to create state with array data type and initial data is empty array. &lt;strong&gt;useState()&lt;/strong&gt; will take initial value as parameter. Here we initialized with empty array. &lt;/p&gt;

&lt;p&gt;Lets use this as part of CharacterSummary functional component to fetch data from API and to store names as part of state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./styles.css";
import React, { useState } from "react";
export default function App() {
  const [characters, setCharactersData] = useState([]);

  const fetchData = async () =&amp;gt; {
    await fetch("https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8")
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; {
        let names = [];
        data.forEach(function (item) {
          names.push(item.name)
        });

        setCharactersData(names);

      });
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;label&amp;gt;Data is&amp;lt;/label&amp;gt;
      &amp;lt;p&amp;gt;{characters}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; fetchData()}&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;In the above component , we are displaying a button in UI. When the above JSX rendered a button will be shown in the UI.Data will be null as state is empty array.&lt;/p&gt;

&lt;p&gt;When we click on button , fetch will get the details from API and all names will be stored  as part of &lt;strong&gt;characters&lt;/strong&gt; state. Same will be displayed in the UI.&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%2Faakjja53z4oh6lwsfvf0.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%2Faakjja53z4oh6lwsfvf0.PNG" alt="UI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Some questions on React.useState()
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What if we want to use more than one state variable&lt;/strong&gt;:-
 Simply use useState() multiple times to declare multiple state variables.
 If you want to use only one useState() variable then declare all variables as a object in one useState(). Sample below.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [multiple, setMultiple] = useState({currentPageBuilds: [],
            downloadedData: [],
            filteredData: [],
            builds: [],
            _sort: 'submittedDate',
            _page: 1,
            _order: 'desc',
            _limit: 10,
            _Type: 0,
            _boxId: '',
            boxName: '',
            selectedRows: { data: [] },
            q: '',
            totalCount: 0,
            loading: false,
            isFiltered: false,
            failure: false,});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can update any variable in this complex state 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; setMultiple({...multiple,failure:true});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Can we use useState() any where&lt;/strong&gt;:-
No, React hooks can be used only at top level. Don’t call Hooks inside loops, conditions, or nested functions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Only call hooks in React functions , not from any Java script functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some more points on useState()&lt;/strong&gt;:-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The update function of useState() doesn’t update the value right away. It is asynchronous.&lt;/li&gt;
&lt;li&gt;If same value is updated to the state, React wont re-render the component  as React uses Object.is to compare the updated state values with previous one.&lt;/li&gt;
&lt;li&gt;In case of complex objects, useState() replaces the objects instead of merging.&lt;/li&gt;
&lt;li&gt;If you use the previous value to update state, you must pass a function that receives the previous value and returns an updated value. Sample below.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setMessage(previousVal =&amp;gt; previousVal + currentVal)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thats all I have reg useState(). Will update the article once i found more details. Thanks.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>html</category>
    </item>
  </channel>
</rss>
