useState Hook
What is useState Hook ?
useState in react helps to manage the states over the application.
Importing useState
To use useState , we have to import it firsts :
1import {useState} from 'react';
Initilizing useStates
You can initialize state like this:
1import { useState } from "react";
2const App = () => {
3 const [cound, setCount] = useState(0);
4};
useState takes initial state as argument and gives a state and a function(setCount in this case) to update that state as we can't directly change/update a state. Also, these state names are just like variables, hence you can name them anything you like.
Reading useStates
We can read and display the value that are present in the states :
1import { useState } from "react";
2const App = () => {
3 const [cound, setCount] = useState(0);
4 return <div>Hello , count value is {count}</div>;
5};
6export default App;
As mentioned earlier, it returns a state and a function to change/update that state. Hence, everything is stored in name. We can read states just like variables:
Updating a State
To update state we use the function it returns to update state, in this case: setCount. State can be updated like this:
1import { useState } from "react";
2const App = () => {
3 const [cound, setCount] = useState(0);
4 setCount(4);
5 return <div>Hello , count value is {count}</div>;
6};
7export default App;
Here , the new value of count will be set to 4. Initially , the value of count was 0 , by default.
States Datatypes
Like any other variables in js , state can hold any datatypes like string, integers, booleans, arrays, object in arrays, arrays in object etc.