Create Counter App With React
Tags: webdev, javascript, beginners, react
Published: 2024-05-15 16:44:51

Hi there :wave. In this article I'll take you through the steps of creating a counter application from React.

Prerequisites
- NPM installed
- Create-react-app installed
- Basic understanding of React's useState hook.

Agenda
- Setting up empty application
- Deleting un required files
- Creating state variables and importing state
- Creating call back functions
- Adding JSX to Counter Component
- A little bit of copy pasting for css
- Done.

Okay, I guess you already have the prerequisites in check. 

First, let's create an empty react application. 

After choosing in which folder you will create the application, enter the following command in your terminal application `npx create-react-app counterapp`.

Execution of this command will take some time to complete but once your done, you'll have something like this.


![Empy Application Created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akan2sojkgg5s6hgqf2e.png)



Now moving on to the next step. Let's delete all these files we won't need for this app. 


![Useless files deleted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4s5c2s6q7ln4zqek99j.png)



I did my deletions from terminal but you can do yours from your IDE if you want to.


Move to the index.js file and delete all the lines higlighted in the snap below.


![Lines to delete from index.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3mkrjqydh74cpo84gy2.png)

That's line 5 and 17

And from the App.js file delete logo import and all the stuff in the return clause of the App component, it should look like so after you are done;

![Clean App.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wyd4gcx9b5klb2rcze3.png)


Now I hope you are still in the App.js file, let's start building the application. 

First, let's create the variable counterVar right at the top of the App functional component to hold the counter's value. Give it a start value of 0.




![Variable Counter Var created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0olia8ftyw11pi493c42.png)




Since we are using state, modify counter to use list destructuring and include a name for the function we shall use to update counter as a state variable. 



![CounterVar as State Variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbe3wprwcphjrcyi99m1.png)







Speaking of state, let's import the `useState` hook from React. We can't use the hook minus importing it. 



![Imported the UseState Hook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztibfss1vdw9sow2ad4p.png)







Ok, now back to the component. Let's set the state's initial state to 0.




![Initializing CounterVar with 0](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2l5huc100w67usvb5s1p.png)






Next will be creating the call back functions. The functions that will be triggered when the buttons of our counter application are clicked.

These will be placed right under the state variable we just defined. 


Let's first create the function to increase counter. 

When we come to creating the decrease function, it won't be any different so we'll copy from this one and only change a few things.



![Increment CallBack](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tye8kvixvez250bjf5r0.png)






So, the increment function uses the state updater function. The state updater function is passed an arrow function where the current value of state is passed and the return value is that current value incremented by one. 


Interested in why an arrow function rather than state itself is passed to the state updater function, [this article](https://dev.to/serifcolakel/mastering-usestate-a-guide-to-avoiding-common-pitfalls-in-react-development-ibp) could be of help to you.

Ok, now to create the decrement function we won't do anything new. Copy paste the increment function and only change increment to decrement and where there is an addition sign, replace with a subraction sign. That's simple.




![Both call back functions created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/frislbnfyojajdmguas5.png)






Moving on to write the html for our application. Since the code isn't much, we shall insert it directly into the App component. We shall not create a separate component for it.

Ok, so in the return clause of the App functional component. Insert the following html. 

```
  <div className='App'>
          <button className='decrease' onClick={decrease}>Decrement</button>
               <span>{counterVar}</span>
          <button className='increase' onClick={increase}>Increment</button>
          </div>


```


We have 2 buttons with a span holding the counter value in between. We use JSX which is denoted by the curly braces to dynamically reflect what is held in the variable in our html code. 

The call back functions for the buttons are given , for each button , to the `onClick`. 


Now the main stuff is out of the way. Our lifeless dull app should now be able to work.
Close App.js and execute `npm run start` to see how things are so far. 



![Functional App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjyzblaryh9ajdadg6ad.gif)





Let's give it some life. We shall now copy paste some CSS into the App.css file. Delete everything you'll  find there and add the css in the code block below. Ctrl-C Ctrl-V. Easy pizzy Nice and Easy. 

```
body {
        background-color: whitesmoke;
}


#root, .App {
        
        display: flex;
        justify-content: center;
        align-items:center;
}       


.App {  
        margin: 40vh; 
 
}

span {
        margin: 0 20px;
        font-size: 1.9em;
}

button {                
        padding: 20px;
        padding-left: 40px;
        width: 220px;
        color: white;
        font-size: 1.1em;
}

.decrease {
        background: red;
}       

.increase {
        background: green;
}



```

Let's give it a run and see how it turns out.


![Designed App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ysd3uyrfjm7bywyxj8m7.gif)



Mine is working. I hope yours is to. If it ain't, please go through  the previous steps and find out if you did not miss anything. 

If the error persists, reach out to me in the comment section or better; utilize the internet and learn some debugging while at it. 

What did we learn in this article. We applied our knowledge on react , useState hook in particular to build a basic counter application. 

You can go on from their to build more creative applications with `useState` and other features React has to offer.

If you got any comments, corrections or suggestions. I am all ears in the comment section. Thanks for reading and  don't forget to subscribe if you found this helpful.

{% embed 
 https://www.youtube.com/embed/6MpF7swF8TE?si=LU42sIrYdVd2iBM4 %}