DEV Community

Esther Adebayo
Esther Adebayo

Posted on

How to use React Hooks to create a Counter Component

Have you been looking for the simplest way to build a counter component using React Hooks? Well, here you go! First thing you need to know is that since we're using hooks, our component would be a functional component(not class component).

This is what we're working towards:
Counter Component
The major things you need to bear in mind are:

i. A way to set the initial state of the component, using the useState hook
ii. Event handlers to handle increment and decrement
iii. Building this Counter Component is very easy.

I'll take you step by step on how to code this. So, let's get started!!!

The first thing to do is import React and useState hook. Like so:

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Next, we create the counter component.

P.S Remember to export it if you'll be rendering it in the App Component.

function Counter(props) {
  return (
    <div>
      <h3>Hello from Counter</h3>
    </div>
  )
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Add the initial state of the component using useState. We would set the initial state to zero, 0.

// Set the initial count state to zero, 0
  const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Add the buttons, onClick handlers and UI display into the jsx of our code:

function Counter(props) {
// Set the initial count state to zero, 0
  const [count, setCount] = useState(0);
  return (
    <div>
      <div>
        <button onClick={handleDecrement}>-</button>
        <h5>Count is {count}</h5>
        <button onClick={handleIncrement}>+</button>
      </div>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  )
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Add the onClick event handlers functionality for both handleIncrement and handleDecrement.

// Create handleIncrement event handler
  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
  };

  //Create handleDecrement event handler
  const handleDecrement = () => {
    setCount(prevCount => prevCount - 1);
  };
Enter fullscreen mode Exit fullscreen mode

Overall, our code looks like this:

import React, { useState } from "react";

function Counter() {
  // Set the initial count state to zero, 0
  const [count, setCount] = useState(0);

  // Create handleIncrement event handler
  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
  };

  //Create handleDecrement event handler
  const handleDecrement = () => {
    setCount(prevCount => prevCount - 1);
  };
  return (
    <div>
      <div>
        <button onClick={handleDecrement}>-</button>
        <h5>Count is {count}</h5>
        <button onClick={handleIncrement}>+</button>
      </div>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Lastly, remember to import our Counter component and render it into App.js like so:

import React from "react";
import Counter from "../Counter";

export default function App() {
  return (
    <div className="App">
      <Counter/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading and I hope you found this helpful.

Top comments (5)

Collapse
 
zingitdev profile image
zinGit-Dev

hello, please, if you can explain, would like to know why
setCount(prevCount => prevCount + 1) and not setCount( count + 1)
pd: amazing post

Collapse
 
dayoolacodes profile image
Dayo Ayoola

setState in the react useState hooks can also take a callback function which has the previous value of that particular state. so you can update the previous value to whatever you want.

Collapse
 
maxim218 profile image
maxim218

I am sorry, but I did not understand the answer about setCount(prevCount => prevCount + 1);
As for me I think, that approach setCount(count + 1) is simplier then your solution.
If I write the code setCount(count + 1) will it correct work, or I am making a mistake
Thank you!

Collapse
 
risyandi profile image
Risyandi

That's great, simple, and helpful.
thanks

Collapse
 
_estheradebayo profile image
Esther Adebayo

Glad you found it useful!