Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to Create a Counter in React.js

How to Create a Counter in React.js

Hello! In this tutorial, you will learn how to create a "counter" application in React.js with the useState hook.


If you are following this tutorial locally and not on Repl.it, please complete the following:

  • A brief understanding of React.js
  • Install Node.js.
  • Create new react app by running $ npx [email protected] my-app.
  • Delete unnecessary files (logo192.png, logo512.png, manifest.json, robots.txt, App.test.js, App.css, index.css, ServiceWorker.js, and SetupTests.js.)
  • In src/index.js, remove the last line of code, as it is also unnecessary.

Getting Started in App.js

First, delete all of the boilerplate code in this file.
To start off, import React and the useState hook from React like so:

Next, let's create our function "App":

Inside of our "App", let's initialize count and setCount as state variables, starting at 0.

Now we can return an empty fragment, and - inside of it - we can return a header 1 and a button that increments count by 1 using our setCount function.

But we're not done yet: we need to create an anonymous function inside of the button tag to actually increment our count variable.

Now, we are finished!