Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 21, 2021 03:25 pm GMT

React useState hook usage

Hi everyone, today we will see how to use React useState hook.

Hooks are a new addition in React 16.8. They let u use state and other React features without writing a class.

Before React 16.8 we don't have state feature usage in functional components as if they were like side characters in React.

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).

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

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.

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,        };

Now we will see how to use useState() in Functional Components.
First we will import the required modules from react.

import React,{useState} from 'react'/*here we have imported the useState to maintain the state of the React component.*/

Now we will create test functional component to use state.

import React,{useState} from 'react'function State() {    return (        <div>        </div>    )}export default State

Now we will create state variable using React.useState() to store data returned by Free JSON API Link.

const [characters, setCharactersData] = useState([]);

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

Lets use this as part of CharacterSummary functional component to fetch data from API and to store names as part of state.

import "./styles.css";import React, { useState } from "react";export default function App() {  const [characters, setCharactersData] = useState([]);  const fetchData = async () => {    await fetch("https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8")      .then((res) => res.json())      .then((data) => {        let names = [];        data.forEach(function (item) {          names.push(item.name)        });        setCharactersData(names);      });  };  return (    <div>      <label>Data is</label>      <p>{characters}</p>      <button onClick={() => fetchData()}>Click</button>    </div>  );}

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.

When we click on button , fetch will get the details from API and all names will be stored as part of characters state. Same will be displayed in the UI.

UI

Some questions on React.useState()

  1. What if we want to use more than one state variable:- 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.
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,});

You can update any variable in this complex state like this.

 setMultiple({...multiple,failure:true});
  1. Can we use useState() any where:-No, React hooks can be used only at top level. Dont call Hooks inside loops, conditions, or nested functions.

Only call hooks in React functions , not from any Java script functions.

Some more points on useState():-

  • The update function of useState() doesnt update the value right away. It is asynchronous.
  • 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.
  • In case of complex objects, useState() replaces the objects instead of merging.
  • 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.
setMessage(previousVal => previousVal + currentVal)

Thats all I have reg useState(). Will update the article once i found more details. Thanks.


Original Link: https://dev.to/pa1sathvik/react-usestate-hook-usage-b8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To