React hooks allows us to use state in function components. I find this method of using state easier than the old class-based version.
Import the useState hook from react before creating a function component. The first thing to do is set the initial state. Assign useState with the desired initial state as the parameter to an array as a const type variable.
const [count, setCount] = useState(0);
In the above example, we create a piece of state called count to store the value of a counter. Inside the array, we place two items – the variable name for the state, and another variable to modify the state. You may name these anything you like, but the convention is to use the name for the state preceded by ‘set’ for the modifier.
The state variable cannot be modified directly. We must use the second variable to change the state (setCount in this example). Attempts to directly change the state will result in an error.
count = count + 1 // will cause an error
setCount(count + 1) // will add 1 to the current state of the count variable.
The state may be passed down to the HTML render via JSX between the { }.
<h3>You clicked {count} times.</h3>
Since we have used the concept of a counter for this example, let us carry on by creating a counter component using the useState hook.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked { count } times!</P>
<button onClick={() => setCount(count + 1)}>Click Me!</button>
Click me!
</button>
</div>
);
}
Clicking the button runs an anonymous arrow function which updates the state of count by calling setCount. This is fine as a simple example, but you may also create the function separately and invoke it from the button.

We may expand our simple counter component by creating two functions, one for addition, another for subtraction. Place these definitions above the return function.
const addCount = () => {
setCount(count + 1)
}
const subtractCount = () => {
setCount(count - 1)
}
Replace the button with two buttons, one for each function:
<button onClick={ addCount }> + </button>
<button onClick={ subtractCount }> - </button>
Here is the final component which now includes a button for addition and another for subtraction:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const addCount = () => {
setCount(count + 1)
}
const subtractCount = () => {
setCount(count - 1)
}
return (
<div>
<p>You clicked { count } times!</P>
<button onClick={ addCount }> - </button>
<button onClick={ subtractCount }> - </button>
Click me!
</button>
</div>
);
}


