Categories
React Projects

Create a Counter App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a counter app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app counter

with NPM to create our React project.

Create the Counter App

To create the counter app, we write:

import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount((c) => c + 1);
  };

  const decrement = () => {
    setCount((c) => c - 1);
  };

  return (
    <div className="App">
      <button onClick={increment}>increment</button>
      <button onClick={decrement}>decrement</button>
      <p>{count}</p>
    </div>
  );
}

We have the count state created by the useState hook.

We set the initial value to 0.

Then we have the increment and decrement functions to increase and decrease count by 1 respectively.

We pass in a function that has the current value of the count state as the parameter and return the new value in the setCount callbacks.

Then we have buttons that calls increment and decrement respectively when we click them.

And we display the count as the result of our clicks.

Conclusion

We can create a counter app with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *