How to create a counter app using functional components in React?

This blog describes how to create a counter app using functional components in React.

To create a counter app using functional components in React, you’ll need to maintain the state of the counter using the useState hook. For example.


import React, { useState } from 'react';

const CounterApp = () => {
  // State variable count and function setCount to update it
  const [count, setCount] = useState(0);

  // Function to increment the count
  const increment = () => {
    setCount(count + 1);

  // Function to decrement the count
  const decrement = () => {
    setCount(count - 1);

  return (
      <h1>Counter App</h1>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>

export default CounterApp;

In this example:

  • We import React and the useState hook from ‘react’.
  • We define a functional component called CounterApp.
  • Inside the CounterApp component, we use the useState hook to create a state variable count initialized to 0, and a function setCount to update its value.
  • We define two functions increment and decrement to handle the increment and decrement of the count state respectively. Inside these functions, we use setCount to update the count state.
  • We render the count state inside a <p> element to display the current count value.
  • We render two buttons, one for incrementing and one for decrementing the count. We attach the increment and decrement functions to the onClick event of these buttons.

This creates a simple counter app where you can increment and decrement the count. Each time you click the buttons, the count state updates, and the component re-renders to reflect the new count value.


import React from 'react';
import ReactDOM from 'react-dom';
import CounterApp from './CounterApp';

const App = () => {
  return (
      <CounterApp />

    <App />

export default App;


Counter App in React
Counter App in React

Further Reading

JUnit Tutorial

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise



You may also like...

Leave a Reply

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