DEV Community

rashmiw333
rashmiw333

Posted on

Understanding Custom Hooks in React with a Simple Counter Example

Introduction:

To understand the concept better, I created a small counter application
in CodeSandbox using two custom hooks:

  • useCounter
  • useLogger

This simple example helped me understand how custom hooks can separate
logic from the UI and make React components easier to manage.

What is a Custom Hook?

A custom hook is a JavaScript function that allows us to reuse logic
that uses React hooks.

Custom hooks usually start with the word use, such as:

  • useCounter
  • useLogger
  • useFetch
  • useLocalStorage

Instead of putting all the logic inside a component, we can move
reusable logic into a custom hook.

1.Creating the useCounter Hook:

The useCounter hook manages the counter state.

It provides three functions:

  • incrementCounter() increases the counter.
  • decrementCounter() decreases the counter.
  • reset() sets the counter back to zero.

The hook returns the counter value and these functions so that a
component can use them.

2.Creating the useLogger Hook:

Whenever the component renders, it logs the current counter value
to the browser console.

For example:
current value of counter 0
current value of counter 1
current value of counter 2

3.Using the Hooks in App.jsx:

Inside App, called useCounter() and get back the counter value
and the three functions.
then passed the counter value to useLogger():
useLogger(counter);

4.What happens when I click Increment?


Initial state:
counter = 0
       ↓
Click Increment
       ↓
incrementCounter()
       ↓
setCounter(counter + 1)
       ↓
counter = 1
       ↓
useLogger(1)
       ↓
Console → current value of counter 1

Enter fullscreen mode Exit fullscreen mode

When I click the Increment button,incrementCounter() updates the
state.
React re-renders the component with the new counter value.
The logger then receives the updated value.

5.Why use a Custom Hook?

This small example helped to understand why custom hooks are useful.

Instead of keeping the counter state and functions directly inside
the component, moved the logic into useCounter.

For example, instead of writing API-fetching logic in multiple
components, we can create a reusable useFetch hook.

6.Learnings:

While building this small example,learned:

  • How custom hooks can extract reusable logic from a component.
  • How useState can be used inside a custom hook.
  • How a custom hook can return both state and functions.
  • How one custom hook can be used alongside another hook.
  • How separating logic from UI can make components easier to understand.

This was a small example, but it helped me understand the concept
before using custom hooks in larger React applications.

Top comments (0)