How to use useCounter hook in ReactJS ?

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.
Let’s understand the use of this hook by a simple-counter example.
Modules Required:
- npm
- create-react-application
Creating 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
Open the src folder and delete the following files:
- logo.svg
- setupTests.js
- App.test.js
- index.css
- reportWebVitals.js
Project Structure: The project should look like this:
Example: The below example will illustrate the use of the useCounter hook in ReactJS:
index.js
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> ); |
App.js
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 |
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/, you will see the following output:



