Use State
Use State is a react Hook .
useState hook is a function which is used to store state value in a functional component.
we can not use in class level component .
It accepts an argument as the initial value of the state.
It returns an array with 2 elements.
- First element is the current value of state.
- Second element is a function to update the state.
we have to use (useState) In side the function and also top of the function.
We import useState first from React :
import React, { useState } from "react";
Later we use useState :
const [currentStateValue, functionToUpdateState] = useState(initialStateValue);
Example:
import React, { useState } from "react";
const NameChange = () => {
const [statevalue, setStatevalue] = useState('ramesh')
const changestate = () =>{
setStatevalue("kumar")
}
return <>
(button onClick={changestate}>change (/button>
{statevalue}
>;
};
export default NameChange;