LetsCreate: React Counter Component

The first step to understanding state in react

Jun 1st, 2022

react

0

React, a JavaScript framework developed by Meta in 2013 and it's used to build user interfaces for front-end web development. It has become one of the most popular frameworks alongside Vue, Angular, svelte and a lot more.

When I started with React, the first thing I thought was ughh yet another framework to learn but honestly after using it for the past couple of years, React has really grown on me. There are a lot of new things that have come into place over the years and I think it has really improved the developer experience. It honestly fun to work with React but there is always that question someone has when getting started -- where do I even begin?

This article assumes that you know the basics of JavaScript and so we will not be defining concepts such as variables, functions, arrays, objects, and objects. We will however be exploring the basics of react and walking through how to create your first react application. We're going to be building a counter application which will allow users to:

  1. see the current count
  2. increment the count
  3. decrement the count
  4. reset the count to 0.

I think React gaining populartity because its written in JSX, a language that combines HTML and JavaScript. jsx allows us to write and inject javascript code into our HTML thereby abstracting away function calls like .createElement. I say this as JSX looks very similar to HTML, however, these two languages are not the same.

Creating the app

Before we get started with creating our react app, you are going to need Node.JS installed on your computer. If you haven't done so already you can head over to the Node JS website and install the latest version of node. Once this is complete you can check the current version of node installed on your computer by running

bash

node -v

We need to initialize our application in the working directory. This can be anywhere but for starters we are going to be on the desktop. React applications can be initizeled in many different ways, but here we're going to be sticking with the basic client-side rendered application. In your command line/ terminal run the following command:

bash

npx i create-react-app counter-app

Running this command will reach out to all the services needed to install the components to required to run a react app and packages inside a folder called counter—app that will be placed in your desktop.

There are a few files that I want to bring your attendtion to:

  1. The ./package.json file stores all the information required to properly install your application on another computer. Information such as the requried dependancies (code/modules that the application you're about to build depends on), the scripts for your application, and a bunch of other information.
  2. ./public folder contains all the public assets for your application. Assets such as imgs, favicons, and the index.html file.
  3. There are also some other boiler plate code such as test files -- files ending in .test.js. It is a good idea to run tests on your application but for the purposes of this demo we are not going to be doing so. Therefore, we are going to remove files like the test files, the index.css (has styles for what you currently see in the web browser → we are going to be creating our own styles in the app.css file). Also remove the SVG file and any reference to it inside the project. The code the the app.js file show now look like the following:

jsx

import react from "react";
const app = () => {
return <div></div>;
};

We are first going to create something for use to view the current counter. Use a paragraph tag and at first we are going to set the to a static value, 0. We are doing this so we can visualize where everything is on the screen — we will later change it to dynamic value. We also need some buttons that will allow us to increment, decrement, and reset the count.

jsx

import react from "react";
const app = () => {
return (
<div>
<p>0</p>
<button>Increment</button>
<button>Decrement</button>
<button>Reset</button>
</div>
);
};

Doing this just puts the buttons on the screen, however, we need a way to actually increment, decrement and reset the count. To do this we are going to create functions that will handle that logic and then we will call those functions when the respective buttons are pressed. In react, the button element(any element for that matter) takes on a onClick event that can the triggered when the element is clicked. onClick takes in a callback function to prevent it from being triggered when the component mounts — the callback function will call the respective functions for the buttons. Add onClick to the buttons and then reference the respective function → we still have to create these functions. Add the following:

jsx

import react from "react";
const app = () => {
return (
<div>
<p>0</p>
<button onClick={() => Increment()}>Increment</button>
<button onClick={() => Decrement()}>Decrement</button>
<button onClick={() => Reset()}>Reset</button>
</div>
);
};
export default app;

Let's think about this, we want to have a value in our app that changes in response to an action. This dynamic value is called state and we first have import the hook that allows us to store & update state. React hooks are very convinient functions that abstract away a lot logic which make our lives (developers) easier when writting an application. It was introduced just after react switched from being written with class components to function components.

Some common react hooks that you will encouter are useState, useEffect, useCallback, useMemo, useRef, and more. You also have the flexibility of writting your own.

We are going to be importing the useState hook from react and then using it in our application. When importing things from the same library we can write them in one line and have it separated by a comma. We do this by adding the following:

jsx

import react, { useState } from "react";

The useState hook returns an array with two values inside; the first value in the array is our actual state variable while the second value is a function we can use to set that state. These name can be set to anything, however, by convention we set the variable names equal to what they are going to refer to in our app → like any other variable name.

jsx

const [count, setCount] = useState(0);

By passing a value into the useState we can set the default value for that state. Above we are setting the default value to 0.

We are going to create the increment, decrement, and reset function which is going to be responsible for incrementing, decrementing, and resetting our counter. The increment function will look something like this:

jsx

const Increment = () => {
setCount(count + 1);
};

Inside the increment function, we are calling the setCount function from our useState hook and passing in count + 1. This is saying that everytime the Increment function is called, we are going to increment the the current count by 1.

While the above code snippet works to update the state of the count, I should also acknowledge that there another way to update the state. You will most often see state updates written using this method the new state relies on the previous state. The following is an example of what I mean:

jsx

const Increment = () => {
setCount((prev) => prev + 1);
};

This has to do with the way react updates state. If we were to call setCount(count+1) 2X inside the increment function, you would notice that it doesn't work as expected. You would likely find that you are only incrementing the count by 1 instead of 2. React batches state updates together, and runs them at the same time. Therefore, the count is not updated and is using the initial value. The demo below to illustrate what I mean when this increment function is called:

jsx

const Increment = () => {
setCount(count + 1);
setCount(count + 1);
};

0

We are going to do the following for the Decrement and Reset function, so you should end up with something like this:

jsx

const Increment = () => {
setCount((prev) => prev + 1);
};
const Decrement = () => {
setCount((prev) => prev - 1);
};
const Reset = () => {
setCount(0);
};

All we have to do now is replace the static value inside the paragraph tag with the dynamic state variable -- Count.

html

--
<p>0</p>
++
<p>{count}</p>

If everything worked out, you should now have a counter application that has the same functionallity as the one below.

0

Congragulations!

We've made it and we've just completed our first React Application!! Yay! We explored the basics of react, described the similarities/differences between JSX & HTML, explored how to get setup with react, and explored the react hook useState.

on this page

creating the appcongragulations!

Last updated November 4th, 2022