> Like we know so far, Hooks let's you use React without classes
useState is a built-in Hook which is use to add state to function component. useState() ALWAYS returns an array with exactly two elements, which we can rename with array destructuring.
The first variable is the value. Very similar with this.state in Class components.
The second variable is a function to update that value. Also very similar to this.setState in Class components.
The final part to useState is the argument that we pass to it. The useState argument is the initial state value. In the counter that we will build next our initial value will be 0 or useState(0).
Now let's make our component.
import { useState } from "react";
const FunctionalComponent = () => {
const [counter, setCounter] = useState(0);
return;
};
export default FunctionalComponent;
We can see the parts we talked about before on this line
const [counter, setCounter] = useState(0);
// counter = variable that is the value
// setCounter = function to update the value
// useState = argument or initial value that we put
For our Counter we will render some heading to show tha numbers and two Buttons that will listen to our clicks and update the State or reset the State to the initial value. Our Component will look somthing like this
import { useState } from "react";
const FunctionalComponent = () => {
const [counter, setCounter] = useState(0);
const increment = () => {
setCounter(counter + 1);
};
const resetCounter = () => {
setCounter(0);
};
return (
<div>
<h1>{counter}</h1>
<button onClick={increment}>Increment</button>
<button className="reset" onClick={resetCounter}>Reset</button>
</div>
);
};
export default FunctionalComponent;
We made two arrow Functions to call the setCounter Function in them and change the Stateon each click on our Buttons.
const increment = () => {
setCounter(counter + 1);
};
const resetCounter = () => {
setCounter(0);
};
When we click on the Increment button we SET the Counter to increment each time by 1. The argument (counter + 1) is equal to (0 + 1) because counter is our Initial value which is 0.
To reset the Counter to 0 we simply call the setCounter Function with argument 0.
Summary
useState returns a pair! The current state value and a function that lets you update it. We use destructuring assignment for arrays for this.
You can call this function from an event handler or somewhere else. The only argument to useState is the initial state, only used during the first render.
Also we can declare multiple hooks in the same component if we want.