DEV Community

Krishna Bhamare
Krishna Bhamare

Posted on

React | Create a custom counter hook.

In React, a hook is a special function that allows you to "hook into" React features. Custom hooks are a way to reuse stateful logic between components.

Here's an example of a simple custom hook that keeps track of the number of times a button has been clicked:

Image description

This hook is a regular JavaScript function that happens to use the useState hook from React. It returns an object with two properties: count and increment. The count property is the current count and the increment method updates the count.

Here's an example of how you can use the useCounter hook in a component:

Image description

  • You can see, how useCounter hook is being imported and used inside the component Counter by calling it and then using the returned object count and increment methods.

  • In this example the component Counter use the hook useCounter on every re-render, which keep the current state of count, onClick event of the button increment the count and it will be reflected inside the component on re-rendering.

Thanks...!!!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay