Building a React Counter: A Beginner's Guide

Vasant MestryVasant Mestry
2 min read

Hello guy’s, today we’re going to create a simple counter application in React. This application will increment the count by one.

Prerequisite

  • Familiarity with JS

  • React Fundamentals (Components , useState and useEffect).

Installation

It is super easy to create react application by using Vite . To create application you have to use below command

npm create vite@latest

hit enter after this command, you’ll be getting few prompts to enter project details as below images

Enter project name and select framework as React

Select variant as JavaScript:

After this do installation using below commands

Now do npm run dev to start the project.

Folder Structure

The folder structure of our will look like this:

Components

Now create 2 folders inside the src folder: one for components and one for hooks.

In the hooks folder, we'll create a useCounter hook. The reason for creating a custom hook is that if we want to use it elsewhere in the code later, it can be done easily, making the code more readable and extendable.

Our hook will look like this:

This hook will receive two arguments: one for the initial count and another for how much the count should be increased. It will return an object with count and an incrementByCount function. This function will be called in the UI by a button click or any event we want to trigger.

Next, we'll create a Counter.jsx file in the components folder. This file will have a button that triggers a click event to increment the count by 1, as shown below.

Here, you can see that we're extracting the count and incrementByCount function from the useCounter hook, which takes two arguments: 0 and INCREMENT_COUNT set to 3.

The final UI looks like this:

Conclusion

I hope you find this article helpful and that it adds value to your coding career.
If you want, you can add more features to this app, like decrementing the count or adding a light/dark theme.
You can check out the full source code here 👈

If you have any suggestions, ideas, or questions, please reach out to me on my social media.

Until next time, happy coding!w

1
Subscribe to my newsletter

Read articles from Vasant Mestry directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vasant Mestry
Vasant Mestry