Creating Counter using React UseState

image.png

We will first Create a Counter.js file and import in the App.js file and use component in our App.js file wherever we want to display the content of Counter.js. we will later learn state and changing it in upcoming section.

App.js

import "./App.css";
import Counter from"./Counter";
export default function App() {

  return (
    <div className="App">
      <h1>Hello React!</h1>

      <Counter/>
    </div>
  );
}

Now it is time to change the state, which are pretty helpful in updating the values of components without rendering the whole page. States are special function in which we can pass values or function. first Let us set our initial state by adding the value in useState as useState(1) i.e. initial state is 1.

Now we will assign this state to counting function and to update the value of this function we will use a function setCounting and when we change the setCounting state it will automatically render and update the current counting state that we can display in our page. The syntax to write this is .

const [counting, SetCounting]= useState(0);

Counter.js

import React , {useState} from "react";

function Counter() {


 const [counting,setCounting] = useState(1);

 add =()=> {
   setCounting(counting+1);
 }
 sub=()=>{
   setCounting(counting-1);
 }
  return (
    <div>
      <h1>Counter in ReactJs</h1>
      <h1>{counting}</h1>
      <button onClick={add} > add 1 </button>
      <button onClick={sub}>decrement 1</button>
    </div>
  );
}
export default Counter;