Last Updated : 01 Dec, 2023
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:
Return Value:
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 Structurepackage.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:
OutputRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4