React hooks are something that are fascinating me to try and use them. Will go in deep from starting, but sticking to today’s topic: Simple counter using React. Let’s dive in:
For a simple counter we need to use useState. How to use?
const [count, setCounter] = useState(0)
We used a count variable that will contain the count. setCounter will be a function that will increment/decrement the count value. useState is passed a 0 which means the counter will start with a 0.
I think this is the only thing that one should need to know.
import React, {useState} from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<div>{count}</div>
<button onClick ={()=>{setCount(count+1)}}>Inc </button>
<button onClick ={()=>{setCount(count-1)}}>Dec </button>
</div>
);
}

Leave a comment