DEV Community

loading...

React useState hook usage

Vutukuri Sathvik
ใƒป3 min read

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

Enter fullscreen mode Exit fullscreen mode

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.
*/
Enter fullscreen mode Exit fullscreen mode

Now we will create test functional component to use state.

import React,{useState} from 'react'

function State() {

    return (
        <div>

        </div>
    )
}

export default State
Enter fullscreen mode Exit fullscreen mode

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

const [characters, setCharactersData] = useState([]);
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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,});
Enter fullscreen mode Exit fullscreen mode

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

 setMultiple({...multiple,failure:true});
Enter fullscreen mode Exit fullscreen mode
  1. Can we use useState() any where:- No, React hooks can be used only at top level. Donโ€™t 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() doesnโ€™t 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)
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)