Jun 18, 2021

A simple counter in React

React Counter App

Hello!

Today we will write our first program in React that will run live on our browser! Don't worry if you haven't ever touched React or JavaScript; by the end of this tutorial you'll understand how easy and simple this tiny program is, with just ~40 lines of code!

Our goal: A counter

Our final goal is to implement a counter which performs the below functionalities:

  • Initial value is 0
  • We must be able to increase its value by 1
  • We must be αble to decrease its value by 1, with the minimum allowed value being 0
  • We must be able to reset its value to 0

Technically in order to satisfy the aforementioned requirements we need to have a variable which will store the counter's state - that's an integer number - and we'll have to show 3 buttons to our UI which will be able to manipulate the state of the counter with actions like increase by 1, decrease by 1 and reset to 0.

At the end of this tutorial, our app will look like as shown in the GIF below.

You can visit the app here: https://8lkyd.csb.app/

demo

Setting up

For the sake of this tutorial, we'll use Codesandbox which provides a sandbox browser environment that allows us to quickly build small JS apps that run live on our browser with cool features like auto-reload on code change and stuff like that. This saves us from the "hassle" of needing to set up a proper environment for our computer in order to run such a simple app, while it's really useful in cases where we just need to try something fast or share code with other colleagues.

Having said all that, let's take a look at how we can set up a React project on Codesandbox.

Create a React Project

In order to start a new project in React, we visit this link: https://codesandbox.io/s/react-new. Like shown in the picture below, what we can see in this screen are splitted in 3 parts: the list of our files to the left, the file that we are currently editting in the middle (in our case App.js) and our app that runs live on the right.

You'll notice that if you make a change to the file App.js, our application will automatically reload with the latest changes to the right. For example, change the text "Hello Codesandbox" to "Hello Stranger" on line 6, and you'll notice our app will automatically refresh.

Regarding the files that are shown on the left part of our screen, we only care (at this tutorial) for the file App.js inside which our React code lives and the file styles.css which we will use to give a basic style to our app.

Codesandbox

Coding 🤖

First of all, our app must be able to maintain and manipulate a state. In our case, it needs to be able to set and maintain a counter so we need a "mean" (tool) in order to be able to save and edit an integer (increase, decrease, reset etc).

The "mean" which we will use for this tutorial is the function, or more correctly in React language the "hook" useState. The React hook useState takes the initial value of our variable as a first argument and a setter function as a second argument with which we're able to set a desired value to it.

In our case, the variable which we call counter, has an initial value of 0, so we can use the useState as shown in the code block below. The counter variable returned from useState contains the value of our counter, while with setCounter we can set the counter to any value we desire.

const [counter, setCounter] = useState(0);

Going on, let's think what functions we need for our counter's functionality? We need a function of increasing by 1, a function of decreasing by 1 and a function of resetting to initial value.

We can construct the aforementioned functions as shown at the code block below.

A quick note here for my experienced React friends: In a real case scenario we would use useCallback and we would set states with callbacks e.g setCounter(c => c+1)

Our functions are increase, decrease and reset. Due to the fact that the minimum allowed value of our counter is 0, we perform a check inside the decrease function if our counter has already reached the minimum allowed value and if it is we show a proper message with the alert function.

const increase = () => {
    setCounter(counter + 1);
};

const decrease = () => {
    if (counter === 0) {
        alert("Counter cannot go below zero!");
        return;
    }
    setCounter(counter - 1);
};

const reset = () => {
    setCounter(0);
};

Our app logic is ready! Let's take a look on how we can show this information on our UI.

Firstly, we must show the current value of our counter on the screen. React allows us to render variables inside HTML surrounding the variable name with {}. So we can show the counter variable inside a <div> block like this:

<div>Counter value: {counter}</div>

Then, we need to show 3 buttons for the increase, decrease and reset of our counter. At each one of those buttons we pass the appropriate function to the onClick button's callback.

<button onClick={() => increase()}>Increase +1</button>
<button onClick={() => decrease()}>Decrease -1</button>
<button onClick={() => reset()}>Reset</button>

Finally, in order to give some basic styling to our app we provide some code to the styles.css file.

Our 2 final files are shown below, and our app is ready to launch! Take a look to the right of your screen and play with the counter we just built!

You can find the complete app's code in this Codesandbox: https://codesandbox.io/s/nifty-elbakyan-8lkyd?file=/src/App.js

App.js:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0);

  const increase = () => {
    setCounter(counter + 1);
  };

  const decrease = () => {
    if (counter === 0) {
      alert("Counter cannot go below zero!");
      return;
    }
    setCounter(counter - 1);
  };

  const reset = () => {
    setCounter(0);
  };

  return (
    <div className="app">
      <h2>Counter App</h2>
      <div className="counter-value">
        <strong>{counter}</strong>
      </div>
      <div className="buttons">
        <div>
          <button onClick={() => increase()}>+</button>
        </div>
        <div>
          <button onClick={() => decrease()}>-</button>
        </div>
        <div>
          <button onClick={() => reset()}>0</button>
        </div>
      </div>
    </div>
  );
}

styles.css:

.app {
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 200px;
  margin: 0 auto;
  padding: 8px;
  border-radius: 8px;
}

h2 {
  margin: 0;
  font-weight: normal;
}

.app > * {
  text-align: center;
  margin-bottom: 8px;
}

.counter-value {
  margin-top: 23px;
  color: #2d2d2d;
  font-size: 30px;
}

.buttons {
  margin: 0 auto;
  margin-top: 23px;
  display: flex;
  justify-content: center;
}

button {
  border-radius: 100%;
  width: 35px;
  height: 35px;
  border: none;
  font-size: 21px;
  background-color: #2c2f3d;
  color: white;
  margin-left: 10px;
  cursor: pointer;
}

button:hover {
  opacity: 0.75;
}

The end

I hope you enjoyed this tutorial. Do not forget to leave a reaction below!

How do you feel that you just created your first web app? 🙂