Create a Simple Counter in React

Last updated: December 24, 2023.

First, we’ll create a new React project using Vite by running the following from the command line:

npm create vite@latest

After setting a project name (e.g. vite-project) and selecting a React > JavaScript project from the options menu.

cd project-name  <# navigates into newly created project-name folder #>
npm install      <# installs boilerplate project dependencies #>
code .           <# opens files in code editor #>
npm run dev      <# starts development server (usually starts on localhost:5173) #>

Creating the counter

As a first step, in App.jsx, we’ll make our application return some static JSX, with a dynamic count value to be added in the next step.

const App = () => {
  return (
    <div>
      <button>-</button>
      <span>0</span>
      <button>+</button>
    </div>
  )
};

export default App;

We can create a dynamic count value, we create a count value using the useState() hook, setting its initial value to 0.

count is inserted into the JSX but is not yet updated when the + or - buttons are clicked:

import { useState } from "react";

const App = () => {

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

  return (
    <div>
      <button>-</button>
      <span>{ count }</span>
      <button>+</button>
    </div>
  )

};

export default App;

In a final step, onClick attributes are added to the + and - buttons, calling the increment() and decrement() functions respectively.

Each of these updates count using its updating function, setCount(). And for each a callback function is inserted into it, in which the current value of count is automatically available as a parameter. The return value of this plus or minus one determines the new value of count when a rerender is triggered by the updating of this state value.

import { useState } from "react";

const App = () => {

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

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

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

  return (
    <div>
      <button onClick={ decrement }>-</button>
      <span>{ count }</span>
      <button onClick={ increment }>+</button>
    </div>
  )

};

export default App;
Tags: