Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to Create a Counter in React.js
SharpCodeDev (80)

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.

Prerequisites

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:

import React, { useState } from 'react';

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

export default function App() {}

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

const [count, setCount] = useState(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.

return (
    <>
        <h1>{count} clicks.</h1>
        <button>Increment Count</button>
    </>
);

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

<button onClick={() => {
    // Increment count by 1. 
    setCount(count + 1);
}>Increment Count</button>

Now, we are finished!