29
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.
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.
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});
Only call hooks in React functions , not from any Java script functions.
Some more points on useState():-
setMessage(previousVal => previousVal + currentVal)
Thats all I have reg useState(). Will update the article once i found more details. Thanks.
29