Open In App

How to use useCounter hook in ReactJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

The useCounter is a custom hook provided by the Rooks package for React. It is a counter hook that helps build a simple counter easily and quickly.

Syntax:

useCounter( initialValue )

Parameters:

  • initialValue: It is of number type that describes the initial value.

Return Value:

  • counter: It is of type object which contains a value, increment, decrement, incrementBy, decrementBy, and reset.

Steps to Create the React Application And Installing Module

Step 1: Create a React application using the following command:

npx create-react-application demo

Step 2: After creating your project folder i.e. demo, move to it using the following command:

cd demo

Step 3: Install Rooks from npm.

npm i rooks

Project Structure:

Project Structure

package.json:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"rooks": "^7.14.1",
"web-vitals": "^2.1.4",
}

Example: The below example will illustrate the use of the useCounter hook in ReactJS:

Javascript




import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);


Javascript




import React from "react";
import "./App.css";
import { useCounter } from "rooks";
 
const App = () => {
    const { value, increment, decrement, incrementBy, decrementBy, reset } =
        useCounter(0);
    return (
        <div>
            <p> Counter</p>
            <p>
                {" "}
                <span>Current value </span>is {value}
            </p>
            <button onClick={increment}>Increment</button>
            <br />
            <br />
            <button onClick={decrement}>Decrement</button>
            <br />
            <br />
            <button onClick={() => incrementBy(2)}>Increase by 2</button>
            <br />
            <br />
            <button onClick={() => decrementBy(2)}>Decrease by 2</button>
            <br />
            <br />
            <button onClick={reset}>reset</button>
        </div>
    );
};
 
export default App;


CSS




/* Write CSS Here */
p {
  margin: 20px;
  font-size: 30px;
  color: rebeccapurple;
  font-weight: bold;
}
 
span {
  color: red;
}
 
button {
  margin: 20px;
  width: 300px;
  font-size: 20px;
  background: rgb(190, 233, 190);
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000:

Output



Last Updated : 01 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads