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...!!!

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay