I am going to explain useState hook in the easiest manner. Code along with me, we will create a simple counter app using useState hook. Hooks are a new addition in React 16.8, UseState hook is one of them.
useState takes 2 arguments, 1st one is your variable which you want to use further in your counter app to assign initial value, and 2nd is a function for setting up/changing your initial value.
now we will use the initial value of our counter from useState which we just defined.
This will show up 0 in our browser as we have assigned 0 in our initial state or variable in useState.
for Counter App, we need two buttons, one for increment and one for decrement. let's just create that. we will add an onClick event in both of our buttons for changing our counter App value. For increment, we will set up :
onClick={() => setCounter(counter + 1)}
For decrement, we will set up :
onClick={() => setCounter(counter - 1)}
now to change our counter app click on one of these two buttons, for increment click on the Increment button counter variable will increment by 1 per click, and to decrement click on the decrement button counter variable will be decremented by 1.
FINAL CODE :
import React, { useState } from "react";
function App() {
const [counter, setCounter] = useState(0);
// counter: variable which has initial value 0
// setCounter : function to change our initial value
return (
<div className="App">
<header className="App-header">
<h1>{counter}</h1>
<button onClick={() => setCounter(counter + 1)}>Increment</button>
<button onClick={() => setCounter(counter - 1)}>decrement </button>
</header>
</div>
);
}
export default App;
you just created Counter App using useState Hook in React