The useState Hook returns the state value and the setter function that will allow us to modify the state value returned.
Below is the syntax for useState Hook:
const [state, setState] = useState(initialState); // this is a Javascript destructuring happing here, useState function will return the state value and assign it to state variable i.e of const type & a setter function as setState.
Basically the below sample code shows the three steps used to implement useState hook.
Step1: import {useState} from 'react'.
// the below code should be inside functional component.
Step2: const [count, setCount] = useState(initialCount); // here useState returns state value and assigns it in count variable, and also return a setter function i.e assigned to setCount variable.
Step3: <button onClick={() => setCount(initialCount)}>Reset</button>; // calling the setCount function to update the initial state.
The below sample code shows the basic implemention of usestate hook for incrementing, decrementing & reseting counter variable in a functional component also making use of previous count value .
//sample code starts here
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount); // returns state variable and setter function & gets assigned using es6(javascript) destructuring.
return (
<> Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button> // here on minus(-) button click the function is getting called, where we are passing a function inside setcount setter function which will provide the previous state value as a first parameter ad then we can make use of it, for our logic as in this case we are using previous state value to update the counter.
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button> </> );
}
// sample code ends here
Thanks.